Template Engine

Beego uses Go’s built-in package html/template as the template parser. Upon startup, it will compile and cache the templates into a map for efficient rendering.

Template Directory

The default template directory for Beego is views. Template files can be put into this directory and Beego will parse and cache them automatically. However, if the development mode is enabled, Beego parses templates every time without caching. Beego can only have one template directory which can be customized:

  1. web.BConfig.WebConfig.ViewsPath = "myviewpath"

You can add alternative template directories by calling

  1. web.AddViewPath("moreViews")

This will parse and cache template files in this directory and allow you to use them by setting ViewPath on a Controller:

  1. this.ViewPath = "moreViews"

Setting a ViewPath to a directory which was not previously registered with AddViewPath() will fail with “Unknown view path”

Auto Rendering

You don’t need to render and output templates manually. Beego will call Render automatically after finishing the method. You can disable auto rendering in the configuration file or in main.go if you don’t need it.

In configuration file:

  1. autorender = false

In main.go:

  1. web.BConfig.WebConfig.AutoRender = false

Template Tags

Go uses {{ and }} as the default template tags. In the case that these tags conflict with other template tags as in AngularJS, we can use other tags. To do so, In configuration file:

  1. templateleft = <<<
  2. templateright = >>>

Or, add these to the main.go:

  1. web.BConfig.WebConfig.TemplateLeft = "<<<"
  2. web.BConfig.WebConfig.TemplateRight = ">>>"

Template Data

Template gets its data from this.Data in Controller. So for example if you write

  1. {{.Content}}

in the template, you need to assign it in the Controller first:

  1. this.Data["Content"] = "value"

Different rendering types:

struct

Struct variable:

  1. type A struct{
  2. Name string
  3. Age int
  4. }

Assign value in the Controller:

  1. this.Data["a"]=&A{Name:"astaxie",Age:25}

Render it in the template:

  1. the username is {{.a.Name}}
  2. the age is {{.a.Age}}

map

Assign value in the Controller:

  1. mp["name"]="astaxie"
  2. mp["nickname"] = "haha"
  3. this.Data["m"]=mp

Render it in the template:

  1. the username is {{.m.name}}
  2. the username is {{.m.nickname}}

slice

Assign value in the Controller:

  1. ss :=[]string{"a","b","c"}
  2. this.Data["s"]=ss

Render it in the template:

  1. {{range $key, $val := .s}}
  2. {{$key}}
  3. {{$val}}
  4. {{end}}

Template Name

From version 1.6: this.TplNames is this.TplName

Beego uses Go’s built-in template engine, so the syntax is same as Go. To learn more about template see Templates.

You can set the template name in Controller and Beego will find the template file under the viewpath and render it automatically. In the config below, Beego will find add.tpl under admin and render it.

  1. this.TplName = "admin/add.tpl"

Beego supports .tpl and .html file extensions by default. If you’re using other extensions, you must set it in the configuration first:

  1. beego.AddTemplateExt("file_extension_you_need")

If TplName is not set in the Controller while autorender is enabled, Beego will use TplName as below by default:

  1. c.TplName = strings.ToLower(c.controllerName) + "/" + strings.ToLower(c.actionName) + "." + c.TplExt

It is Controller name + “/“ + request method name + “.” + template extension. So if the Controller name is AddController, request method is POST and the default template extension is tpl, Beego will render /viewpath/addcontroller/post.tpl template file.

Layout Design

Beego supports layout design. For example, if in your application the main navigation and footer does not change and only the content part is different, you can use a layout like this:

  1. this.Layout = "admin/layout.html"
  2. this.TplName = "admin/add.tpl"

In layout.html you must set a variable like this:

  1. {{.LayoutContent}}

Beego will parse the file named TplName and assign it to LayoutContent then render layout.html.

Beego will cache all the template files. You can also implement a layout this way:

  1. {{template "header.html"}}
  2. Logic code
  3. {{template "footer.html"}}

LayoutSection

LayoutContent is a little complicated, as it can include Javascript and CSS. Since in most situations having only one LayoutContent is not enough, there is an attribute called LayoutSections in Controller. It allows us to set multiple section in Layout page and each section can contain its own sub-template page.

layout_blog.tpl:

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <title>Lin Li</title>
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  7. <link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css">
  8. <link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap-theme.min.css">
  9. {{.HtmlHead}}
  10. </head>
  11. <body>
  12. <div class="container">
  13. {{.LayoutContent}}
  14. </div>
  15. <div>
  16. {{.SideBar}}
  17. </div>
  18. <script type="text/javascript" src="http://code.jquery.com/jquery-2.0.3.min.js"></script>
  19. <script src="http://netdna.bootstrapcdn.com/bootstrap/3.0.3/js/bootstrap.min.js"></script>
  20. {{.Scripts}}
  21. </body>
  22. </html>

html_head.tpl:

  1. <style>
  2. h1 {
  3. color: red;
  4. }
  5. </style>

scripts.tpl:

  1. <script type="text/javascript">
  2. $(document).ready(function() {
  3. // bla bla bla
  4. });
  5. </script>

Here is the logic in the Controller:

  1. type BlogsController struct {
  2. web.Controller
  3. }
  4. func (this *BlogsController) Get() {
  5. this.Layout = "layout_blog.tpl"
  6. this.TplName = "blogs/index.tpl"
  7. this.LayoutSections = make(map[string]string)
  8. this.LayoutSections["HtmlHead"] = "blogs/html_head.tpl"
  9. this.LayoutSections["Scripts"] = "blogs/scripts.tpl"
  10. this.LayoutSections["Sidebar"] = ""
  11. }

Another approach

We can also just specify the template the controller is going to use and let the template system handle the layout:

for example:

controller:

  1. this.TplName = "blog/add.tpl"
  2. this.Data["SomeVar"] = "SomeValue"
  3. this.Data["Title"] = "Add"

template add.tpl:

  1. {{ template "layout_blog.tpl" . }}
  2. {{ define "css" }}
  3. <link rel="stylesheet" href="/static/css/current.css">
  4. {{ end}}
  5. {{ define "content" }}
  6. <h2>{{ .Title }}</h2>
  7. <p> This is SomeVar: {{ .SomeVar }}</p>
  8. {{ end }}
  9. {{ define "js" }}
  10. <script src="/static/js/current.js"></script>
  11. {{ end}}

layout_blog.tpl:

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <title>{{ .Title }}</title>
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  7. <link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css">
  8. <link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap-theme.min.css">
  9. {{ block "css" . }}{{ end }}
  10. </head>
  11. <body>
  12. <div class="container">
  13. {{ block "content" . }}{{ end }}
  14. </div>
  15. <script type="text/javascript" src="http://code.jquery.com/jquery-2.0.3.min.js"></script>
  16. <script src="http://netdna.bootstrapcdn.com/bootstrap/3.0.3/js/bootstrap.min.js"></script>
  17. {{ block "js" . }}{{ end }}
  18. </body>
  19. </html>

Using block action instead of template allows us to have default block content and skipping blocks that we don’t need in every template (for example, if we don’t need css block in add.tpl template - we will not define it and that won’t raise an error)

renderform

Define struct:

  1. type User struct {
  2. Id int `form:"-"`
  3. Name interface{} `form:"username"`
  4. Age int `form:"age,text,age:"`
  5. Sex string
  6. Intro string `form:",textarea"`
  7. }
  • StructTag definition uses form as tag. There are three optional params separated by ‘,’:

    • The first param is name attribute of the form field. If empty, it will use struct field name as the value.
    • The second param is the form field type. If empty, it is assumed as text.
    • The third param is the tag of form field. If empty, it will use struct field name as the tag name.
  • If the form tag only has one value, it is the name attribute of the form field. Except last value can be ignore all the other place must be separated by ‘,’. E.g.: form:",,username:"

  • To ignore a field there are two ways:

    • The first way is to use lowercase for the field name in the struct.
    • The second way is to set - as the value of form tag.

controller:

  1. func (this *AddController) Get() {
  2. this.Data["Form"] = &User{}
  3. this.TplName = "index.tpl"
  4. }

The param of Form must be a pointer to a struct.

template:

  1. <form action="" method="post">
  2. {{.Form | renderform}}
  3. </form>

The code above will generate the form below:

  1. Name: <input name="username" type="text" value="test"></br>
  2. Age: <input name="age" type="text" value="0"></br>
  3. Gender: <input name="Sex" type="text" value=""></br>
  4. Intro: <input name="Intro" type="textarea" value="">