// HTML renders the HTTP template specified by its file name.
// It also updates the HTTP code and sets the Content-Type as "text/html".
// See http://golang.org/doc/articles/wiki/
514300
func (c *Context) HTML(code int, name string, obj interface{}) {
	instance := c.engine.HTMLRender.Instance(name, obj)
	c.Render(code, instance)
}
705337
func (t *TemplateRenderable) Render(_ ...string) string {
	return string(t.cache.Bytes())
}
154719
func (c *Context) HTML(status int, name string) {
	log.Trace("Template: %s", name)
	c.Context.HTML(status, name)
}
833423
func (ctx *Context) OkHTML(str string) error {
	return ctx.HTML(http.StatusOK, str)
}
359385
func (d *Dataset) HTML() *Exportable {
	back := d.Records()
	b := newBuffer()

	b.WriteString("<table class=\"table table-striped\">\n\t<thead>")
	for i, r := range back {
		b.WriteString("\n\t\t<tr>")
		for _, c := range r {
			tag := "td"
			if i == 0 {
				tag = "th"
			}
			b.WriteString("\n\t\t\t<" + tag + ">")
			b.WriteString(c)
			b.WriteString("</" + tag + ">")
		}
		b.WriteString("\n\t\t</tr>")
		if i == 0 {
			b.WriteString("\n\t</thead>\n\t<tbody>")
		}
	}
	b.WriteString("\n\t</tbody>\n</table>")

	return newExportable(b)
}
972693
func (t Text) Render(w io.Writer, v interface{}) error {
	if hw, ok := w.(http.ResponseWriter); ok {
		c := hw.Header().Get(ContentType)
		if c != "" {
			t.Head.ContentType = c
		}
		t.Head.Write(hw)
	}

	w.Write([]byte(v.(string)))
	return nil
}
580976
func (r *HealthRecord) HTML() template.HTML {
	switch {
	case r.Error != nil:
		return template.HTML(fmt.Sprintf("unhealthy: %v", r.Error))
	case r.ReplicationDelay > *degradedThreshold:
		return template.HTML(fmt.Sprintf("unhappy: %v behind on replication", r.ReplicationDelay))
	default:
		html := "healthy"
		if r.ReplicationDelay > 0 {
			html += fmt.Sprintf(": only %v behind on replication", r.ReplicationDelay)
		}
		if r.IgnoredError != nil {
			html += fmt.Sprintf(" (ignored error: %v, matches expression: %v)", r.IgnoredError, r.IgnoreErrorExpr)
		}
		return template.HTML(html)
	}
}
627651
func (h HTML) Render(w io.Writer, binding interface{}) error {
	// Retrieve a buffer from the pool to write to.
	out := bufPool.Get()
	err := h.Templates.ExecuteTemplate(out, h.Name, binding)
	if err != nil {
		return err
	}

	if hw, ok := w.(http.ResponseWriter); ok {
		h.Head.Write(hw)
	}
	out.WriteTo(w)

	// Return the buffer to the pool.
	bufPool.Put(out)
	return nil
}
1059022
func (view *View) Render(loaderName string, filePath string, data map[string]interface{}) (string, error) {
	loader, ok := view.templateLoader[loaderName]
	if !ok {
		panic(errors.New("Template loader not found: " + loaderName))
	}
	var buf bytes.Buffer
	err := loader.Render(&buf, filePath, data)
	if err != nil {
		return "", err
	}
	return buf.String(), nil
}
401170
func (br BuilderRef) RenderHTML(buffer *bytes.Buffer, depth int, maxDepth int) {
	// If render the HTML as flat rather than nested, we don't need to recurse at all and should just
	// return after rendering the BuilderSummary.
	if maxDepth < 0 {
		if br.Builder != nil && br.Builder.LastFinishedBuildID != "" {
			must(fmt.Fprintf(buffer, `<a class="console-builder-status" href="%s" title="%s">`,
				template.HTMLEscapeString(br.Builder.LastFinishedBuildIDLink()),
				template.HTMLEscapeString(br.Builder.BuilderID),
			))
			must(fmt.Fprintf(buffer, `<div class="console-list-builder status-%s"></div>`,
				template.HTMLEscapeString(br.Builder.LastFinishedStatus.String()),
			))
		} else {
			must(fmt.Fprintf(buffer, `<a class="console-builder-status" href="/%s" title="%s">`,
				template.HTMLEscapeString(br.ID),
				template.HTMLEscapeString(br.ID),
			))
			must(buffer.WriteString(`<div class="console-list-builder"></div>`))
		}
		must(buffer.WriteString(`</a>`))
		return
	}

	must(buffer.WriteString(`<div class="console-builder-column">`))
	// Add spaces if we haven't hit maximum depth to keep the grid consistent.
	for i := 0; i < (maxDepth - depth); i++ {
		must(buffer.WriteString(`<div class="console-space"></div>`))
	}
	must(buffer.WriteString(`<div>`))
	var extraStatus string
	if br.Builder != nil {
		extraStatus += fmt.Sprintf("console-%s", br.Builder.LastFinishedStatus)
	}
	must(fmt.Fprintf(
		buffer, `<span class="%s"><a class="console-builder-item" href="%s" title="%s">%s</a></span>`,
		template.HTMLEscapeString(extraStatus),
		template.HTMLEscapeString(br.Builder.SelfLink()),
		template.HTMLEscapeString(br.BuilderName()),
		template.HTMLEscapeString(br.ShortName)))
	must(buffer.WriteString(`</div>`))

	must(buffer.WriteString(`<div class="console-build-column">`))

	status := "None"
	link := "#"
	class := ""

	// Below is a state machine for rendering a single builder's column.
	// In essence, the state machine takes 3 inputs: the current state, and
	// the if the next 2 builds exist. It uses this information to choose the
	// next state.
	//
	// Each iteration, the state machine writes out the state's corresponding element,
	// either a lone cell, the top of a long cell, the bottom of a long cell, the
	// middle of a long cell, or an empty space.
	//
	// The ultimate goal of this state machine is to visually extend a single
	// build down to the next known build for this builder by commit.

	// Initialize state machine state.
	//
	// Could equivalently be implemented using a "start" state, but
	// that requires a no-render special case which would make the
	// state machine less clean.
	var state int
	switch {
	case len(br.Build) == 1:
		switch {
		case br.Build[0] != nil:
			state = cell
		case br.Build[0] == nil:
			state = empty
		}
	case len(br.Build) > 1:
		switch {
		case br.Build[0] != nil && br.Build[1] != nil:
			state = cell
		case br.Build[0] != nil && br.Build[1] == nil:
			state = top
		case br.Build[0] == nil:
			state = empty
		}
	default:
		// This is probably a console preview.
	}
	// Execute state machine for determining cell type.
	for i, build := range br.Build {
		nextBuild := false
		if i < len(br.Build)-1 {
			nextBuild = br.Build[i+1] != nil
		}
		nextNextBuild := false
		if i < len(br.Build)-2 {
			nextNextBuild = br.Build[i+2] != nil
		}

		var nextState int
		switch state {
		case empty:
			class = "empty-cell"
			switch {
			case nextBuild && nextNextBuild:
				nextState = cell
			case nextBuild && !nextNextBuild:
				nextState = top
			case !nextBuild:
				nextState = empty
			}
		case top:
			class = "cell-top"
			status = build.Summary.Status.String()
			link = build.SelfLink()
			switch {
			case nextNextBuild:
				nextState = bottom
			case !nextNextBuild:
				nextState = middle
			}
		case middle:
			class = "cell-middle"
			switch {
			case nextNextBuild:
				nextState = bottom
			case !nextNextBuild:
				nextState = middle
			}
		case bottom:
			class = "cell-bottom"
			switch {
			case nextNextBuild:
				nextState = cell
			case !nextNextBuild:
				nextState = top
			}
		case cell:
			class = "cell"
			status = build.Summary.Status.String()
			link = build.SelfLink()
			switch {
			case nextNextBuild:
				nextState = cell
			case !nextNextBuild:
				nextState = top
			}
		default:
			panic("Unrecognized state")
		}
		// Write current state's information.
		must(fmt.Fprintf(buffer,
			`<div class="console-cell-container"><a class="console-%s status-%s" href="%s" title="%s">`+
				`<span class="console-cell-text">%s</span></a><div class="console-cell-spacer"></div></div>`,
			class, status, link,
			template.HTMLEscapeString(br.BuilderName()),
			br.ShortName))

		// Update state.
		state = nextState
	}
	must(buffer.WriteString(`</div></div>`))
}
943727
func chunksToHTML(chunks []formatChunk) template.HTML {
	buf := bytes.Buffer{}
	for _, chunk := range chunks {
		if len(chunk.html) != 0 {
			buf.WriteString(string(chunk.html))
		} else {
			buf.WriteString(template.HTMLEscapeString(chunk.str))
		}
	}
	return template.HTML(buf.String())
}
277879
func (w *Widget) Render(context *Context, file string) template.HTML {
	var (
		err     error
		content []byte
		tmpl    *template.Template
	)

	if file == "" {
		file = w.Templates[0]
	}

	defer func() {
		if r := recover(); r != nil {
			err = fmt.Errorf("Get error when render file %v: %v", file, r)
			utils.ExitWithMsg(err)
		}
	}()

	if content, err = context.Widgets.AssetFS.Asset(file + ".tmpl"); err == nil {
		if tmpl, err = template.New(filepath.Base(file)).Funcs(context.FuncMaps).Parse(string(content)); err == nil {
			var result = bytes.NewBufferString("")
			if err = tmpl.Execute(result, context.Options); err == nil {
				return template.HTML(result.String())
			}
		}
	}

	return template.HTML(err.Error())
}
787091
func (md Markdown) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error) {
	var cfg *Config
	for _, c := range md.Configs {
		if httpserver.Path(r.URL.Path).Matches(c.PathScope) { // not negated
			cfg = c
			break // or goto
		}
	}
	if cfg == nil {
		return md.Next.ServeHTTP(w, r) // exit early
	}

	// We only deal with HEAD/GET
	switch r.Method {
	case http.MethodGet, http.MethodHead:
	default:
		return http.StatusMethodNotAllowed, nil
	}

	var dirents []os.FileInfo
	var lastModTime time.Time
	fpath := r.URL.Path
	if idx, ok := httpserver.IndexFile(md.FileSys, fpath, md.IndexFiles); ok {
		// We're serving a directory index file, which may be a markdown
		// file with a template.  Let's grab a list of files this directory
		// URL points to, and pass that in to any possible template invocations,
		// so that templates can customize the look and feel of a directory.
		fdp, err := md.FileSys.Open(fpath)
		switch {
		case err == nil: // nop
		case os.IsPermission(err):
			return http.StatusForbidden, err
		case os.IsExist(err):
			return http.StatusNotFound, nil
		default: // did we run out of FD?
			return http.StatusInternalServerError, err
		}
		defer fdp.Close()

		// Grab a possible set of directory entries.  Note, we do not check
		// for errors here (unreadable directory, for example).  It may
		// still be useful to have a directory template file, without the
		// directory contents being present.  Note, the directory's last
		// modification is also present here (entry ".").
		dirents, _ = fdp.Readdir(-1)
		for _, d := range dirents {
			lastModTime = latest(lastModTime, d.ModTime())
		}

		// Set path to found index file
		fpath = idx
	}

	// If not supported extension, pass on it
	if _, ok := cfg.Extensions[path.Ext(fpath)]; !ok {
		return md.Next.ServeHTTP(w, r)
	}

	// At this point we have a supported extension/markdown
	f, err := md.FileSys.Open(fpath)
	switch {
	case err == nil: // nop
	case os.IsPermission(err):
		return http.StatusForbidden, err
	case os.IsExist(err):
		return http.StatusNotFound, nil
	default: // did we run out of FD?
		return http.StatusInternalServerError, err
	}
	defer f.Close()

	fs, err := f.Stat()
	if err != nil {
		return http.StatusGone, nil
	}
	lastModTime = latest(lastModTime, fs.ModTime())

	ctx := httpserver.Context{
		Root: md.FileSys,
		Req:  r,
		URL:  r.URL,
	}
	html, err := cfg.Markdown(title(fpath), f, dirents, ctx)
	if err != nil {
		return http.StatusInternalServerError, err
	}

	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	w.Header().Set("Content-Length", strconv.Itoa(len(html)))
	httpserver.SetLastModifiedHeader(w, lastModTime)
	if r.Method == http.MethodGet {
		w.Write(html)
	}
	return http.StatusOK, nil
}
155285
func renderTpl(writer io.Writer, name string, data interface{}) error {
	if tpl == nil {
		return errors.New("Rendering template error! Please compile your templates.")
	}

	return tpl.ExecuteTemplate(writer, name, data)
}
1096799
func (acetmpl AceTemplate) Render(wr io.Writer, arg interface{}) error {
	// We can redirect this render to another template if the arguments contain ace_content in them
	if argmap, ok := arg.(map[string]interface{}); ok {
		if acecontentraw, ok := argmap["ace-inner"]; ok {
			acecontent := acecontentraw.(string)
			newtemplatename := acetmpl.TemplateName + "-" + acecontent
			// Now lookup the template again
			if _, ok := acetmpl.engine.templatesByName[newtemplatename]; !ok {
				if inner, ok := acetmpl.engine.templatesByName[acecontent]; !ok {
					return fmt.Errorf("Inner content %s not found in ace templates", acecontent)
				} else {
					acetmpl.engine.templatesByName[newtemplatename] = &AceTemplate{
						File:         acetmpl.File,
						Inner:        inner.File,
						engine:       acetmpl.engine,
						TemplateView: acetmpl.TemplateView}
				}

			}
			return acetmpl.engine.templatesByName[newtemplatename].renderInternal(wr, arg)
		}
	}
	return acetmpl.renderInternal(wr, arg)
}
767999
func Render(w io.Writer, tpl string, data interface{}) error {
	templateFuncs := template.FuncMap{
		"last": func(x int, a interface{}) bool {
			return x == reflect.ValueOf(a).Len()-1
		},
	}
	tplParsed := template.Must(template.New("render").Funcs(templateFuncs).Parse(tpl))
	return tplParsed.Execute(w, data)
}
1107137
func (r *Render) Text(w io.Writer, status int, v string) error {
	head := Head{
		ContentType: r.opt.TextContentType + r.compiledCharset,
		Status:      status,
	}

	t := Text{
		Head: head,
	}

	return r.Render(w, t, v)
}