GF Framework Template engine-basic usage

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

Article Source: http://gf.johng.cn/591642

Controller view

GF provides a good template engine support for the controller, managed by the gmvc.View view object, providing good data isolation. The controller view is a concurrency-safe design that allows asynchronous operations in multiple threads.

func (view *View) Assign(key string, value interface{})func (view *View) Assigns(data map[string]interface{})func (view *View) Parse(file string) ([]byte, error)func (view *View) ParseContent(content string) ([]byte, error)func (view *View) Display(files ...string) errorfunc (view *View) DisplayContent(content string) errorfunc (view *View) LockFunc(f func(vars map[string]interface{}))func (view *View) RLockFunc(f func(vars map[string]interface{}))

Using Example 1:

package mainimport (    "gitee.com/johng/gf/g/net/ghttp"    "gitee.com/johng/gf/g/frame/gmvc")type ControllerTemplate struct {    gmvc.Controller}func (c *ControllerTemplate) Info() {    c.View.Assign("name", "john")    c.View.Assigns(map[string]interface{}{        "age"   : 18,        "score" : 100,    })    c.View.Display("index.tpl")}func main() {    s := ghttp.GetServer()    s.BindController("/template", &ControllerTemplate{})    s.SetPort(8199)    s.Run()}

index.tplthe template content is as follows:

After execution, access http://127.0.0.1:8199/template/info can see that the template is parsed and displayed on the page. If the page error can not find the template file, there is no relationship, because there is no template directory settings, the default is the current executable directory (Linux&mac is the /tmp directory under Windows C:\Documents and Settings\用户名\Local Settings\Temp ). How to manually set the template file directory see the next sections, and then you can go back to manually modifying the table of contents to see the results.

Where the file parameter of the given template files is required with the full file name suffix, for example: index.tpl , and index.html so on, the template engine does not require the template file suffix name, the user can be fully customized. In addition, the template file parameter also supports the absolute path of the file (full file path).

Of course, we can also directly parse the template content, see Example 2:

package mainimport (    "gitee.com/johng/gf/g/net/ghttp"    "gitee.com/johng/gf/g/frame/gmvc")type ControllerTemplate struct {    gmvc.Controller}func (c *ControllerTemplate) Info() {    c.View.Assign("name", "john")    c.View.Assigns(map[string]interface{}{        "age"   : 18,        "score" : 100,    })    c.View.DisplayContent(`        

After execution, http://127.0.0.1:8199/template/info the access can be seen after parsing the following content:

Non-controller view

The use of the template engine in a non-controller is not supported by the Controller view and can be implemented using the underlying Gview package, which can be used to obtain the default Singleton Gview object using the Singleton manager.

Gview Package Method List:

func Get(path string) *Viewfunc New(path string) *Viewfunc (view *View) BindFunc(name string, function interface{})func (view *View) Parse(file string, params map[string]interface{}) ([]byte, error)func (view *View) ParseContent(content string, params map[string]interface{}) ([]byte, error)func (view *View) GetPath() stringfunc (view *View) SetPath(path string)

Using Example 1:

package mainimport (    "gitee.com/johng/gf/g/net/ghttp"    "gitee.com/johng/gf/g/frame/gins")func main() {    s := ghttp.GetServer()    s.BindHandler("/template2", func(r *ghttp.Request){        content, _ := gins.View().Parse("index.tpl", map[string]interface{}{            "id"   : 123,            "name" : "john",        })        r.Response.Write(content)    })    s.SetPort(8199)    s.Run()}

In this example we use the Singleton Manager to get a default view object, which is then used to render the template file under the corresponding template directory index.tpl and given the template variable parameters.

We can also SetPath specify the template directory of the View object through the method center, which is concurrency-safe, but it is important to note that once the template directory for that view object is changed, it will take effect throughout the process.

Of course, you can also parse the template content directly, using Example 2:

package mainimport (    "gitee.com/johng/gf/g/net/ghttp"    "gitee.com/johng/gf/g/frame/gins")func main() {    s := ghttp.GetServer()    s.BindHandler("/template2", func(r *ghttp.Request){        tplcontent := `id:{{.id}}, name:{{.name}}`        content, _ := gins.View().ParseContent(tplcontent, map[string]interface{}{            "id"   : 123,            "name" : "john",        })        r.Response.Write(content)    })    s.SetPort(8199)    s.Run()}

After execution, the access http://127.0.0.1:8199/template2 can see the parsed content as:id:123, name:john

Also, it is important to note that while the above examples are presented in Web server, the template engine is an intelligent parsing of template files/content that can be used in any scenario.

Modify Template Catalog

As the core component of the GF framework, the template engine can modify the template engine's default template file lookup directory in the following ways:

    1. (recommended) Singleton mode gets the global view object, which is SetPath manually modified by method
    2. Modify command-line startup Parameters-viewpath
    3. Modifies the specified environment variable-gf.viewpath

For example, our execution program file is main, so you can modify the template directory (under Linux) in the following ways:

    1. (recommended) By single-case mode

      gins.View().SetPath("/opt/template")
    2. Through command-line arguments

      ./main --viewpath=/opt/template/
    3. Through environment variables

      • Modify environment variables at startup:

        gf.viewpath=/opt/config/; ./main
      • Use the GENV package to modify environment variables:

        genv.Set("gf.viewpath", "/opt/template")

Automatically detect updates

The template engine uses a caching mechanism that, when the template file is read for the first time, is cached to memory, and the next read is fetched directly from the cache to improve execution efficiency. Also, the template engine provides a mechanism for automatic detection of template files, and when the template file is externally modified, the template engine can instantly monitor and refresh the cached content of the template file.

The automatic detection and update mechanism of the template engine is also a feature of the GF framework.

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.