Rendering

This document only applies when using https://github.com/gobuffalo/buffalo/render.
Please see github.com/gobuffalo/plush for more details on the underlying templating package.

Renderer Interface

In order for a renderer to be able to be used with Context#Render it must implement the following interface:

// Renderer interface that must be satisified to be used with
// buffalo.Context.Render
type Renderer interface {
  ContentType() string
  Render(io.Writer, Data) error
}

// Data type to be provided to the Render function on the
// Renderer interface.

type Data map[string]interface{}

Thankfully the https://github.com/gobuffalo/buffalo/render [godoc] package implements that interface, and has a collection of useful render types already defined. It is recommended that you use this package, but feel free and write your own renderers!

Creating a Render Engine

A render engine is used to store information about configuration needed for rendering. Examples include: helpers, layouts, etc. Multiple engines can be initialized. For example one engine for the "main" site, and another for the "admin" portion.

By default an initial render engine is created for the application during application generation:

var r *render.Engine

func init() {
  r = render.New(render.Options{
    HTMLLayout: "application.html",
    TemplatesBox: packr.NewBox("../templates"),
    Helpers: render.Helpers{},
  })

}

Markdown

Files passed into the render.HTML or render.Template functions, that have an extension of .md, will be converted from Markdown (using GitHub flavored Markdown) to HTML before being run through the templating engine. This makes for incredibly easy templating for simpler pages.

// beatles.md
# The Beatles

<%= for (name) in names { %>
* <%= name %>
<% } %>
// actions/beatles.go
func Beatles(c buffalo.Context) error {
  c.Set("names", []string{"John", "Paul", "George", "Ringo"})
  return c.Render(200, r.HTML("beatles.md"))
}
// output
<h1>The Beatles

<ul>
  <li>John
  <li>Paul
  <li>George
  <li>Ringo
</ul>

Automatic extensions

since v0.10.2

You can use HTML, Javascript and Markdown renderers without specifing the file extension:

// actions/beatles.go
func Beatles(c buffalo.Context) error {
  c.Set("names", []string{"John", "Paul", "George", "Ringo"})
  // Render beatles.html
  return c.Render(200, r.HTML("beatles"))
}

This works with partials too.

Copyright © 2017 Buffalo. All rights reserved.

Buffalo Gopher designed by Ashley McNamara — Original Gopher designed by Renee French.