golang template syntax does not resolve the html tags and special characters

Scenes

Sometimes the need to use the template syntax go, for example to render html page with go time, for example, and then engage in when using code generation templates go. This time may encounter a trouble, do not want the special character translation is a translation.

I encountered was when the write code generator, '<' sign is translated, resulting in part of the channel-related problems.

The problem is simple, but not much information, I also tried for a long time only to find. In fact, a string that contains special characters to turn into template.HTML type to a file and then load it.

solve

Look at the code

    t := template.New("initMysql")
    
    type NsqConsumerTpl struct {
        Names        []string
        AngleBracket template.HTML
    }
    
    v := NsqConsumerTpl{
        Names: nsqConsumerIns, 
        AngleBracket:template.HTML("<")
        
    }
        

First we declare a template, and then declare a structure for rendering the template. Its AngleBracket field is the field of special characters are not translated in a template. Here, I used to put '<' up.

The following code statement template section, and direct reference to this field within the template, this time '<' will not be translated.

    tpl := `func (p *NsqConsumerMgr) Start() error {
        {{range .Names}}
        err := p.{{.}}.ConnectToNSQLookupds(p.{{.}}.LookupAddr)
        if err != nil {
            panic(err)
        }
        {{end}}
    
        ch := make(chan bool)
        {{ .AngleBracket }}-ch
        return nil
    }`

    t.Execute(tpl, v)

If you use more than one place, you can put forward a function

Defined functions, the function is very simple, to turn into temp.HTML type str.

func unescaped (str string) template.HTML { return template.HTML(str) }

The function is registered to the template:

    t = t.Funcs(template.FuncMap{"unescaped": unescaped})

At this time, the structure used for rendering, special characters can be directly used string

    type NsqConsumerTpl struct {
        Names        []string
        AngleBracket string
    }

The template is slightly different, {{.AngleBracket | unescaped}} This is a means: by a channel (channel conceptually similar linux) AngleBracket as the parameters passed to the function unescaped.

func (p *NsqConsumerMgr) Start() error {
    {{range .Names}}
    err := p.{{.}}.ConnectToNSQLookupds(p.{{.}}.LookupAddr)
    if err != nil {
        panic(err)
    }
    {{end}}

    ch := make(chan bool)
    {{ .AngleBracket | unescaped}}-ch
    return nil
}
    t.Execute(tpl, v)

Speaking relatively simple, but little information, check more strenuous, then summed up with this, to share.
Welcome to add

Remember harvest point like oh ~

Guess you like

Origin www.cnblogs.com/mingbai/p/goTmpl.html