How to create a global variable and change in multiple places in golang html/template?

大城市里の小女人 提交于 2019-11-26 21:43:38

问题


I am creating a variable in html/template and and changing the value based on a condition. But the scope of the value stays only inside the if condition:

{{if .UserData}}
    {{$currentUserId := .UserData.UserId}}
    [<a href="#ask_question">Inside {{$currentUserId}}</a>]
{{else}}
    {{$currentUserId := 0}}
{{end}}
[<a href="#ask_question">outside {{$currentUserId}}</a>]

Inside the if condition I am getting the correct value but outside it is 0. How can I use the $currentUserIdoutside the condition? Could someone help me with this?


回答1:


Short answer is: you can't.

By design philosophy, templates should not contain complex logic. In templates you can only create new variables, you cannot change the values of existing template variables. When you do {{$currentUserId := .UserData.UserId}} inside an {{if}} block, that creates a new variable which shadows the outer one, and its scope extends to the {{end}} action.

This is described in the text/template package, Variables section (the same applies to the html/template package too):

A variable's scope extends to the "end" action of the control structure ("if", "with", or "range") in which it is declared, or to the end of the template if there is no such control structure. A template invocation does not inherit variables from the point of its invocation.

Possible workarounds

Easiest in your case would be to register a custom function CurrentUserId() to your template, which if UserData is present, returns its id UserData.UserId(), and if it is not present, returns 0 as in your case.

This is an example how it can be done:

type UserData struct {
    UserId int
}

func main() {
    m := map[string]interface{}{}
    t := template.Must(template.New("").Funcs(template.FuncMap{
        "CurrentUserId": func() int {
            if u, ok := m["UserData"]; ok {
                return u.(UserData).UserId
            }
            return 0
        },
    }).Parse(src))

    if err := t.Execute(os.Stdout, m); err != nil {
        panic(err)
    }
    m["UserData"] = UserData{99}
    if err := t.Execute(os.Stdout, m); err != nil {
        panic(err)
    }
}

const src = `Current user id: {{CurrentUserId}}
`

It first executes the template without UserData, then it executes the template with UserData having UserId = 99. The output is:

Current user id: 0
Current user id: 99

Try it on the Go Playground.

Simulating changeable variables

You can also simulate changeable variables, but also with registered custom function(s). You could register a function like SetCurrentUserId() which would change the value of a variable, preferably in the params that is passed to the template execution so it remains safe for concurrent use.

This is an example how to do it (it uses a map as template data, and SetCurrentUserId() sets the current user id as a value in this map):

func main() {
    m := map[string]interface{}{}
    t := template.Must(template.New("").Funcs(template.FuncMap{
        "SetCurrentUserId": func(id int) string {
            m["CurrentUserId"] = id
            return ""
        },
    }).Parse(src))

    if err := t.Execute(os.Stdout, m); err != nil {
        panic(err)
    }
    m["UserData"] = UserData{99}
    if err := t.Execute(os.Stdout, m); err != nil {
        panic(err)
    }
}

const src = `Before: {{.CurrentUserId}}
{{if .UserData}}
    {{SetCurrentUserId .UserData.UserId}}Inside: {{.CurrentUserId}}
{{else}}
    {{SetCurrentUserId 0}}Inside: {{.CurrentUserId}}
{{end}}
After: {{.CurrentUserId}}
`

This again first executes the template without UserData, then it executes the template with UserData having UserId = 99. The output is:

Before: 
    Inside: 0
After: 0
Before: 0
    Inside: 99
After: 99

Try it on the Go Playground.



来源:https://stackoverflow.com/questions/36521839/how-to-create-a-global-variable-and-change-in-multiple-places-in-golang-html-tem

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!