Common basic syntax for Golang templates (template)

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

Common basic syntax for Golang templates (template)

Template

In the dynamic page of the site, we often put the immutable part of the template, the variable part through the back-end program rendering to generate dynamic Web pages, Golang provides a html/template package to support Template rendering.

This article does not discuss the Golang back end of the template reading and rendering methods, only the template embedded variables, rendering variables, loops and some basic usage.

Variable

When Golang renders the template, it can accept a variable of type interface{}, and we can read the value inside the variable and render it to the template in the template file.

There are two common types of incoming parameters. One is a struct that can be rendered by reading the contents of the struct domain within the template. There is also a map[string]interface{}, which can be rendered using key within the template.

I generally use the second kind, the efficiency may be a little bit less, but with convenience.

The syntax support embedded in the template, all need to add {{}} to tag.

Within the template file,. Represents the current variable, that is, in a non-circular body, which represents the variable passed in. Suppose we define a struct:

type Article struct {    ArticleId int    ArticleContent string}

So we can get through the template

<p>{{.ArticleContent}}<span>{{.ArticleId}}</span></p>

To get and render the contents of the variable inside the template. Assuming that the contents of the above structure are articleid:1 articlecontent: "Hello", the corresponding rendered template content is:

<p>hello<span>1</span></p>

Isn't it simple?

Of course, we sometimes need to define variables, such as we need to define a article variable and initialize it as "Hello", so we can write:

{{$article := "hello"}}

Suppose we want to assign the contents of an incoming value to article, you can write this:

{{$article := .ArticleContent}}

This allows us to get the contents of this variable as long as {{$article}} is used.

Function

Golang templates are limited in function, and many complex logic cannot be expressed directly using template syntax, so you can use only template functions to bypass them.

First, the template package is supported when creating new templates. The Funcs method is used to import a custom collection of functions into the template, and subsequent files rendered through the template support the direct invocation of these functions.

The function collection is defined as:

type FuncMap map[string]interface{}

Key is the name of the method, and value is the function. There is no limit to the number of arguments for the function, but there is a limit to the return value. There are two options, one with only one return value and one with two return values, but the second return value must be of type error. The difference between the two functions is that the second function is called in the template, assuming that the return of the second parameter of the template function is not NULL, then the render step will be interrupted and an error is given.

Within the template file, the invocation method is also very simple:

{{funcname .arg1 .arg2}}

Let's say we define a function.

func add(left int, right int) int

Within the template file, by invoking the

{{add 1 2}}

You can get

3

As a result, Golang's predefined function has no add, so it's a bit of a hassle.

Judge

The Golang template also supports the if conditional judgment, which currently supports the simplest bool type and string type.

{{if .condition}}{{end}}

True indicates execution when. condition is of type bool, and non-null indicates execution when. condition is a string type.

Of course also supports else, else if nested

{{if .condition1}}{{else if .contition2}}{{end}}

We need some built-in template functions to do this, assuming that we need logical judgments, such as with or without the size, and so on, some of the built-in template functions currently used are:

    • Not non-

      {{if not. Condition}}
      {{End}}

    • And and

      {{if and. condition1. Condition2}}
      {{End}}

    • OR OR

      {{if or. condition1. Condition2}}
      {{End}}

    • EQ equals

      {{if Eq. var1. var2}}
      {{End}}

    • NE is not equal to

      {{if ne. var1. var2}}
      {{End}}

    • LT is smaller than (less than)

      {{if Lt. var1. Var2}}
      {{End}}

    • Le is less than or equal

      {{if Le. var1. var2}}
      {{End}}

    • GT Greater than

      {{if GT. var1. Var2}}
      {{End}}

    • GE is greater than or equal

      {if GE. var1. var2}}
      {{End}}

Cycle

The Golang template supports a range loop to traverse the contents of the map and slice, with the following syntax:

{{range $i, $v := .slice}}{{end}}

Within this range, we can access the traversed values through i V, as well as a way to iterate:

{{range .slice}}{{end}}

The value of index or key cannot be accessed in this way, and it needs to be passed. To access the corresponding value

{{range .slice}}{{.field}}{{end}}

Of course it's used here. To access the traversed values, what do we do if we want to access the external variables? (such as the variables passed in by the render template), where we need to use $. To access external variables

{{range .slice}}{{$.ArticleContent}}{{end}}

Nesting of templates

When writing templates, we often integrate common templates, such as navigation bars and footers on each page, and we often write them as a separate module so that all the pages are imported so that you don't have to write them again.

Any Web page has a master template, and then we can embed a child template within the main template to implement module sharing.

When the template wants to introduce a sub-template, we use the following statement:

{{template "navbar"}}

This will try to load a sub-template named NavBar, and we have to define a sub-template to implement the "NavBar" sub-template.

The child template is defined as:

{{define "navbar"}}{{end}}

The contents between the definitions will overwrite {{template ' NavBar '}}

Of course, the child template is separated, then the child template can get the parent template variables? This is of course, we just need to use

{{template "navbar" .}}

You can pass the current variable to the child template, which is quite handy.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.