Use Golang's standard library to build websites--3. Template functions

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

Similar to the template syntax for most languages: {. Name | FuncName}}
The go itself comes with some template functions, so let's take a look at how to customize the template functions:
Let's look at a function declaration:

func (t *Template) Funcs(funcMap FuncMap) *Template

The Funcs function is the function used to create our template function, which requires a parameter of type FUNCMAP to continue reading the manual

typemap[string]interface{}

That's how it's explained in the official documentation.

Funcmap is the type of the map defining the mapping from names to functions. Each function must had either a single return value, or both return values of which the second has type error. In this case, if the second (error) argument evaluates to Non-nil during execution, execution terminates and Execute retur NS that error.

A simple translation is
This is a map, the name and function of the map, where key corresponds to the function you use in the template name, not necessarily and you in the source code file
The name of the function named in the definition of this map, it is important to note that this is the value of a interface{} type, but it should actually give it a
The function name of the specified type, which is this function:

func functionName(args ...interfacestring

You can also have a second return value, but it must be of type error. If the function executes without error, the value must be nil,
Let's take a look at the specific ways to use:

  func  Index (w http. Responsewriter, R *http. Request) {//map to save data  data: =  make  ( map  [ string ]  string) //Save template function  Tempfunc: =  make  (template. FUNCMAP) tempfunc[ "ShowName" ] = ShowName T, _: = template. Parsefiles ( "index.html" ) //Register template function  t = T.funcs (tempfunc) data[ "Name" ] =  "BCL"  T.execute (w, data)} //This example function, wrap the incoming string with * * * * * *   func  showname (args ...  interface  {})  string  {//Only one parameter is considered here   var  str  String  =  ""   if  s, OK: = args  [0 ]. ( string ); OK {str =  "* * * * *"  + S +  "* * * * *" }  else  {str =  "Nothing"  }  return  str} 

If so, it doesn't seem to be a problem, and the compilation will pass,
Open browser access, found to appear in addition to the problem:
[4]
And the following error has occurred:

2015/07/22 22:38:07 http:panic serving 127.0.0.1:37346:runtime error:invalid memory address or nil pointer dereference
Goroutine 5 [Running]:
Net/http.func 011 ()
/opt/go/src/net/http/server.go:1130 +0XBB
Html/template. (*template). Funcs (0x0, 0XC20803AF30, 0x1)
/opt/go/src/html/template/template.go:276 +0x1f
Main. Index (0x7fda0d28a278, 0xc20804cc80, 0xc208032d00)
/home/buchenglei/workspace/golang/src/test/test.go:18 +0x121
Net/http. Handlerfunc.servehttp (0x7cee28, 0x7fda0d28a278, 0xc20804cc80, 0xc208032d00)
/opt/go/src/net/http/server.go:1265 +0x41
Net/http. (*servemux). Servehttp (0XC20803AA20, 0x7fda0d28a278, 0xc20804cc80, 0xc208032d00)
/opt/go/src/net/http/server.go:1541 +0x17d
Net/http.serverhandler.servehttp (0xc208070060, 0x7fda0d28a278, 0xc20804cc80, 0xc208032d00)
/opt/go/src/net/http/server.go:1703 +0x19a
Net/http. (*conn). Serve (0XC20804CBE0)
/opt/go/src/net/http/server.go:1204 +0xb57
Created by Net/http. (*server). Serve
/opt/go/src/net/http/server.go:1751 +0x35e

Functions that need to overwrite template parsing

func Index(w http.ResponseWriter, r *http.Request) {    //用于保存数据的map    make(map[string]string)    make(template.FuncMap)    tempfunc["showname"] = ShowName    //得给模板起个名字才行    t := template.New("index.html")    t = t.Funcs(tempfunc)    t, _ = t.ParseFiles("./index.html")    data["Name""BCL"    t.Execute(w, data)}

This will give you the correct output results.

Attention

If the string to be exported to the template is an HTML fragment, it will be escaped, and the solution is to use template. HTML () wraps the HTML fragment and sends it to the template for parsing, which ensures that the HTML code is executed correctly by the browser.

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.