Golang template variable isset

Multi tool use
Multi tool use












5















I have created a function to check if a variable is defined:



fm["isset"] = func(a interface{}) bool {
if a == nil || a == "" || a == 0 {
fmt.Println("is not set")
return false
}
fmt.Println("is set")
return false
}

tmpl := template.Must(template.New("").Funcs(fm).ParseFiles("templates/header.html"))

err := tmpl.ExecuteTemplate(w, "header", templateData)


In the template I have:



{{ if isset .Email }}
email is set
{{ end }}


This function works if the variable is contained by the templateData (which is a custom struct that contains a map and a string), but it gives me an error if the variable doesn't exist.



The error is:



executing "header" at <.Email>: can't evaluate field Email in type base.customData


In my case "base.go" is the handler and "customData" is defined by: type customData struct{..}.



I want to be able to reuse templates and to display some sections only if some variables are sent from the handler. Any idea how can I implement a variable isset check on the template side?



I also tried using: {{ if .Email}} do stuff {{ end }} but this also gives me the same error.



Any idea?










share|improve this question

























  • Try to log a in your isset function. Do you see what you are passing in? If not, there is a problem at the template level. Maybe try passing in both the struct and the key to access it on to check if isset, and modify your function accordingly to take in both arguments.

    – Lansana
    Jun 21 '17 at 11:46













  • if my struct contains the "Email" it will work and it will log it inside the isset function. If the struct don't contain "Email" (this is my case) it will just output the error from above, no logs from the issset function will be displayed.

    – Pascut
    Jun 21 '17 at 11:49











  • PHP has the isset($variable) function which returns true/false, what about GO? How can I check for a variable in the template to see if it is sent from the handler? For example, I want to display a menu only if the user is logged in.

    – Pascut
    Jun 21 '17 at 11:51











  • Try simply {{ if .Email }}, that should work for you.

    – Lansana
    Jun 21 '17 at 11:51








  • 1





    Take a look here.

    – Lansana
    Jun 21 '17 at 12:08
















5















I have created a function to check if a variable is defined:



fm["isset"] = func(a interface{}) bool {
if a == nil || a == "" || a == 0 {
fmt.Println("is not set")
return false
}
fmt.Println("is set")
return false
}

tmpl := template.Must(template.New("").Funcs(fm).ParseFiles("templates/header.html"))

err := tmpl.ExecuteTemplate(w, "header", templateData)


In the template I have:



{{ if isset .Email }}
email is set
{{ end }}


This function works if the variable is contained by the templateData (which is a custom struct that contains a map and a string), but it gives me an error if the variable doesn't exist.



The error is:



executing "header" at <.Email>: can't evaluate field Email in type base.customData


In my case "base.go" is the handler and "customData" is defined by: type customData struct{..}.



I want to be able to reuse templates and to display some sections only if some variables are sent from the handler. Any idea how can I implement a variable isset check on the template side?



I also tried using: {{ if .Email}} do stuff {{ end }} but this also gives me the same error.



Any idea?










share|improve this question

























  • Try to log a in your isset function. Do you see what you are passing in? If not, there is a problem at the template level. Maybe try passing in both the struct and the key to access it on to check if isset, and modify your function accordingly to take in both arguments.

    – Lansana
    Jun 21 '17 at 11:46













  • if my struct contains the "Email" it will work and it will log it inside the isset function. If the struct don't contain "Email" (this is my case) it will just output the error from above, no logs from the issset function will be displayed.

    – Pascut
    Jun 21 '17 at 11:49











  • PHP has the isset($variable) function which returns true/false, what about GO? How can I check for a variable in the template to see if it is sent from the handler? For example, I want to display a menu only if the user is logged in.

    – Pascut
    Jun 21 '17 at 11:51











  • Try simply {{ if .Email }}, that should work for you.

    – Lansana
    Jun 21 '17 at 11:51








  • 1





    Take a look here.

    – Lansana
    Jun 21 '17 at 12:08














5












5








5


1






I have created a function to check if a variable is defined:



fm["isset"] = func(a interface{}) bool {
if a == nil || a == "" || a == 0 {
fmt.Println("is not set")
return false
}
fmt.Println("is set")
return false
}

tmpl := template.Must(template.New("").Funcs(fm).ParseFiles("templates/header.html"))

err := tmpl.ExecuteTemplate(w, "header", templateData)


In the template I have:



{{ if isset .Email }}
email is set
{{ end }}


This function works if the variable is contained by the templateData (which is a custom struct that contains a map and a string), but it gives me an error if the variable doesn't exist.



The error is:



executing "header" at <.Email>: can't evaluate field Email in type base.customData


In my case "base.go" is the handler and "customData" is defined by: type customData struct{..}.



I want to be able to reuse templates and to display some sections only if some variables are sent from the handler. Any idea how can I implement a variable isset check on the template side?



I also tried using: {{ if .Email}} do stuff {{ end }} but this also gives me the same error.



Any idea?










share|improve this question
















I have created a function to check if a variable is defined:



fm["isset"] = func(a interface{}) bool {
if a == nil || a == "" || a == 0 {
fmt.Println("is not set")
return false
}
fmt.Println("is set")
return false
}

tmpl := template.Must(template.New("").Funcs(fm).ParseFiles("templates/header.html"))

err := tmpl.ExecuteTemplate(w, "header", templateData)


In the template I have:



{{ if isset .Email }}
email is set
{{ end }}


This function works if the variable is contained by the templateData (which is a custom struct that contains a map and a string), but it gives me an error if the variable doesn't exist.



The error is:



executing "header" at <.Email>: can't evaluate field Email in type base.customData


In my case "base.go" is the handler and "customData" is defined by: type customData struct{..}.



I want to be able to reuse templates and to display some sections only if some variables are sent from the handler. Any idea how can I implement a variable isset check on the template side?



I also tried using: {{ if .Email}} do stuff {{ end }} but this also gives me the same error.



Any idea?







if-statement go struct go-templates






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jun 21 '17 at 12:44









icza

166k25330364




166k25330364










asked Jun 21 '17 at 11:41









PascutPascut

1,42021740




1,42021740













  • Try to log a in your isset function. Do you see what you are passing in? If not, there is a problem at the template level. Maybe try passing in both the struct and the key to access it on to check if isset, and modify your function accordingly to take in both arguments.

    – Lansana
    Jun 21 '17 at 11:46













  • if my struct contains the "Email" it will work and it will log it inside the isset function. If the struct don't contain "Email" (this is my case) it will just output the error from above, no logs from the issset function will be displayed.

    – Pascut
    Jun 21 '17 at 11:49











  • PHP has the isset($variable) function which returns true/false, what about GO? How can I check for a variable in the template to see if it is sent from the handler? For example, I want to display a menu only if the user is logged in.

    – Pascut
    Jun 21 '17 at 11:51











  • Try simply {{ if .Email }}, that should work for you.

    – Lansana
    Jun 21 '17 at 11:51








  • 1





    Take a look here.

    – Lansana
    Jun 21 '17 at 12:08



















  • Try to log a in your isset function. Do you see what you are passing in? If not, there is a problem at the template level. Maybe try passing in both the struct and the key to access it on to check if isset, and modify your function accordingly to take in both arguments.

    – Lansana
    Jun 21 '17 at 11:46













  • if my struct contains the "Email" it will work and it will log it inside the isset function. If the struct don't contain "Email" (this is my case) it will just output the error from above, no logs from the issset function will be displayed.

    – Pascut
    Jun 21 '17 at 11:49











  • PHP has the isset($variable) function which returns true/false, what about GO? How can I check for a variable in the template to see if it is sent from the handler? For example, I want to display a menu only if the user is logged in.

    – Pascut
    Jun 21 '17 at 11:51











  • Try simply {{ if .Email }}, that should work for you.

    – Lansana
    Jun 21 '17 at 11:51








  • 1





    Take a look here.

    – Lansana
    Jun 21 '17 at 12:08

















Try to log a in your isset function. Do you see what you are passing in? If not, there is a problem at the template level. Maybe try passing in both the struct and the key to access it on to check if isset, and modify your function accordingly to take in both arguments.

– Lansana
Jun 21 '17 at 11:46







Try to log a in your isset function. Do you see what you are passing in? If not, there is a problem at the template level. Maybe try passing in both the struct and the key to access it on to check if isset, and modify your function accordingly to take in both arguments.

– Lansana
Jun 21 '17 at 11:46















if my struct contains the "Email" it will work and it will log it inside the isset function. If the struct don't contain "Email" (this is my case) it will just output the error from above, no logs from the issset function will be displayed.

– Pascut
Jun 21 '17 at 11:49





if my struct contains the "Email" it will work and it will log it inside the isset function. If the struct don't contain "Email" (this is my case) it will just output the error from above, no logs from the issset function will be displayed.

– Pascut
Jun 21 '17 at 11:49













PHP has the isset($variable) function which returns true/false, what about GO? How can I check for a variable in the template to see if it is sent from the handler? For example, I want to display a menu only if the user is logged in.

– Pascut
Jun 21 '17 at 11:51





PHP has the isset($variable) function which returns true/false, what about GO? How can I check for a variable in the template to see if it is sent from the handler? For example, I want to display a menu only if the user is logged in.

– Pascut
Jun 21 '17 at 11:51













Try simply {{ if .Email }}, that should work for you.

– Lansana
Jun 21 '17 at 11:51







Try simply {{ if .Email }}, that should work for you.

– Lansana
Jun 21 '17 at 11:51






1




1





Take a look here.

– Lansana
Jun 21 '17 at 12:08





Take a look here.

– Lansana
Jun 21 '17 at 12:08












2 Answers
2






active

oldest

votes


















5














The recommended way



First, the recommended way is not to rely on whether a struct field exists. Of course there might be optional parts of the template, but the condition to decide whether to render a part should rely on fields that exist in all cases.



The issue, and avoiding it using a map



If the type of the template data is a struct (or a pointer to a struct) and there is no field or method with the given name, the template engine returns an error for that.



You could easily get rid of this error if you were to use a map, as maps can be indexed with keys they don't contain, and the result of that index expression is the zero value of the value type (and not an error).



To demonstrate, see this example:



s := `{{if .Email}}Email is: {{.Email}}{{else}}Email is NOT set.{{end}}`

t := template.Must(template.New("").Parse(s))
exec := func(name string, param interface{}) {
fmt.Printf("n%s:n ", name)
if err := t.Execute(os.Stdout, param); err != nil {
fmt.Println("Error:", err)
}
}

exec("Filled map", map[string]interface{}{"Email": "as@as"})
exec("Empty map", map[string]interface{}{})

exec("Filled struct", struct {
Email string
}{Email: "as@as.com"})
exec("Empty struct", struct{}{})


Output (try it on the Go Playground):



Filled map:
Email is: as@as
Empty map:
Email is NOT set.
Filled struct:
Email is: as@as.com
Empty struct:
Error: template: :1:5: executing "" at <.Email>: can't evaluate field Email in type struct {}


Sticking to struct and providing "isset"



If you must or want to stick to a struct, this "isset" can be implemented and provided, I'll call it avail().



This implementation uses reflection, and in order to check if the field given by its name exists (is available), the (wrapper) data must also be passed to it:



func avail(name string, data interface{}) bool {
v := reflect.ValueOf(data)
if v.Kind() == reflect.Ptr {
v = v.Elem()
}
if v.Kind() != reflect.Struct {
return false
}
return v.FieldByName(name).IsValid()
}


Example using it:



s := `{{if (avail "Email" .)}}Email is: {{.Email}}{{else}}Email is unavailable.{{end}}`

t := template.Must(template.New("").Funcs(template.FuncMap{
"avail": avail,
}).Parse(s))
exec := func(name string, param interface{}) {
fmt.Printf("n%s:n ", name)
if err := t.Execute(os.Stdout, param); err != nil {
fmt.Println("Error:", err)
}
}

exec("Filled struct", struct {
Email string
}{Email: "as@as.com"})
exec("Empty struct", struct{}{})


Output (try it on the Go Playground):



Filled struct:
Email is: as@as.com
Empty struct:
Email is unavailable.





share|improve this answer


























  • Thanks for the details and the examples!

    – Pascut
    Jun 21 '17 at 12:52



















0














If you don't send data containing a variable to the template but you use {{ if .Variable }} you will get the error:




executing "templatename" at <.Variable>: can't evaluate field Variable in type handler.Data




My solution was to send the "Email" variable as a boolean (false) in order to pass the {{ if .Email }} function check. But this is a short term solution that I don't like.



I was inspired by: https://stackoverflow.com/a/31527618/1564840. In that example they show different HTML for authenticated and non-authenticated users. You will see that in both cases they send the "Logged" variable. Try removing that variable from the struct and execute the function. You will receive the error that I mentioned above.






share|improve this answer

























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f44675087%2fgolang-template-variable-isset%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    5














    The recommended way



    First, the recommended way is not to rely on whether a struct field exists. Of course there might be optional parts of the template, but the condition to decide whether to render a part should rely on fields that exist in all cases.



    The issue, and avoiding it using a map



    If the type of the template data is a struct (or a pointer to a struct) and there is no field or method with the given name, the template engine returns an error for that.



    You could easily get rid of this error if you were to use a map, as maps can be indexed with keys they don't contain, and the result of that index expression is the zero value of the value type (and not an error).



    To demonstrate, see this example:



    s := `{{if .Email}}Email is: {{.Email}}{{else}}Email is NOT set.{{end}}`

    t := template.Must(template.New("").Parse(s))
    exec := func(name string, param interface{}) {
    fmt.Printf("n%s:n ", name)
    if err := t.Execute(os.Stdout, param); err != nil {
    fmt.Println("Error:", err)
    }
    }

    exec("Filled map", map[string]interface{}{"Email": "as@as"})
    exec("Empty map", map[string]interface{}{})

    exec("Filled struct", struct {
    Email string
    }{Email: "as@as.com"})
    exec("Empty struct", struct{}{})


    Output (try it on the Go Playground):



    Filled map:
    Email is: as@as
    Empty map:
    Email is NOT set.
    Filled struct:
    Email is: as@as.com
    Empty struct:
    Error: template: :1:5: executing "" at <.Email>: can't evaluate field Email in type struct {}


    Sticking to struct and providing "isset"



    If you must or want to stick to a struct, this "isset" can be implemented and provided, I'll call it avail().



    This implementation uses reflection, and in order to check if the field given by its name exists (is available), the (wrapper) data must also be passed to it:



    func avail(name string, data interface{}) bool {
    v := reflect.ValueOf(data)
    if v.Kind() == reflect.Ptr {
    v = v.Elem()
    }
    if v.Kind() != reflect.Struct {
    return false
    }
    return v.FieldByName(name).IsValid()
    }


    Example using it:



    s := `{{if (avail "Email" .)}}Email is: {{.Email}}{{else}}Email is unavailable.{{end}}`

    t := template.Must(template.New("").Funcs(template.FuncMap{
    "avail": avail,
    }).Parse(s))
    exec := func(name string, param interface{}) {
    fmt.Printf("n%s:n ", name)
    if err := t.Execute(os.Stdout, param); err != nil {
    fmt.Println("Error:", err)
    }
    }

    exec("Filled struct", struct {
    Email string
    }{Email: "as@as.com"})
    exec("Empty struct", struct{}{})


    Output (try it on the Go Playground):



    Filled struct:
    Email is: as@as.com
    Empty struct:
    Email is unavailable.





    share|improve this answer


























    • Thanks for the details and the examples!

      – Pascut
      Jun 21 '17 at 12:52
















    5














    The recommended way



    First, the recommended way is not to rely on whether a struct field exists. Of course there might be optional parts of the template, but the condition to decide whether to render a part should rely on fields that exist in all cases.



    The issue, and avoiding it using a map



    If the type of the template data is a struct (or a pointer to a struct) and there is no field or method with the given name, the template engine returns an error for that.



    You could easily get rid of this error if you were to use a map, as maps can be indexed with keys they don't contain, and the result of that index expression is the zero value of the value type (and not an error).



    To demonstrate, see this example:



    s := `{{if .Email}}Email is: {{.Email}}{{else}}Email is NOT set.{{end}}`

    t := template.Must(template.New("").Parse(s))
    exec := func(name string, param interface{}) {
    fmt.Printf("n%s:n ", name)
    if err := t.Execute(os.Stdout, param); err != nil {
    fmt.Println("Error:", err)
    }
    }

    exec("Filled map", map[string]interface{}{"Email": "as@as"})
    exec("Empty map", map[string]interface{}{})

    exec("Filled struct", struct {
    Email string
    }{Email: "as@as.com"})
    exec("Empty struct", struct{}{})


    Output (try it on the Go Playground):



    Filled map:
    Email is: as@as
    Empty map:
    Email is NOT set.
    Filled struct:
    Email is: as@as.com
    Empty struct:
    Error: template: :1:5: executing "" at <.Email>: can't evaluate field Email in type struct {}


    Sticking to struct and providing "isset"



    If you must or want to stick to a struct, this "isset" can be implemented and provided, I'll call it avail().



    This implementation uses reflection, and in order to check if the field given by its name exists (is available), the (wrapper) data must also be passed to it:



    func avail(name string, data interface{}) bool {
    v := reflect.ValueOf(data)
    if v.Kind() == reflect.Ptr {
    v = v.Elem()
    }
    if v.Kind() != reflect.Struct {
    return false
    }
    return v.FieldByName(name).IsValid()
    }


    Example using it:



    s := `{{if (avail "Email" .)}}Email is: {{.Email}}{{else}}Email is unavailable.{{end}}`

    t := template.Must(template.New("").Funcs(template.FuncMap{
    "avail": avail,
    }).Parse(s))
    exec := func(name string, param interface{}) {
    fmt.Printf("n%s:n ", name)
    if err := t.Execute(os.Stdout, param); err != nil {
    fmt.Println("Error:", err)
    }
    }

    exec("Filled struct", struct {
    Email string
    }{Email: "as@as.com"})
    exec("Empty struct", struct{}{})


    Output (try it on the Go Playground):



    Filled struct:
    Email is: as@as.com
    Empty struct:
    Email is unavailable.





    share|improve this answer


























    • Thanks for the details and the examples!

      – Pascut
      Jun 21 '17 at 12:52














    5












    5








    5







    The recommended way



    First, the recommended way is not to rely on whether a struct field exists. Of course there might be optional parts of the template, but the condition to decide whether to render a part should rely on fields that exist in all cases.



    The issue, and avoiding it using a map



    If the type of the template data is a struct (or a pointer to a struct) and there is no field or method with the given name, the template engine returns an error for that.



    You could easily get rid of this error if you were to use a map, as maps can be indexed with keys they don't contain, and the result of that index expression is the zero value of the value type (and not an error).



    To demonstrate, see this example:



    s := `{{if .Email}}Email is: {{.Email}}{{else}}Email is NOT set.{{end}}`

    t := template.Must(template.New("").Parse(s))
    exec := func(name string, param interface{}) {
    fmt.Printf("n%s:n ", name)
    if err := t.Execute(os.Stdout, param); err != nil {
    fmt.Println("Error:", err)
    }
    }

    exec("Filled map", map[string]interface{}{"Email": "as@as"})
    exec("Empty map", map[string]interface{}{})

    exec("Filled struct", struct {
    Email string
    }{Email: "as@as.com"})
    exec("Empty struct", struct{}{})


    Output (try it on the Go Playground):



    Filled map:
    Email is: as@as
    Empty map:
    Email is NOT set.
    Filled struct:
    Email is: as@as.com
    Empty struct:
    Error: template: :1:5: executing "" at <.Email>: can't evaluate field Email in type struct {}


    Sticking to struct and providing "isset"



    If you must or want to stick to a struct, this "isset" can be implemented and provided, I'll call it avail().



    This implementation uses reflection, and in order to check if the field given by its name exists (is available), the (wrapper) data must also be passed to it:



    func avail(name string, data interface{}) bool {
    v := reflect.ValueOf(data)
    if v.Kind() == reflect.Ptr {
    v = v.Elem()
    }
    if v.Kind() != reflect.Struct {
    return false
    }
    return v.FieldByName(name).IsValid()
    }


    Example using it:



    s := `{{if (avail "Email" .)}}Email is: {{.Email}}{{else}}Email is unavailable.{{end}}`

    t := template.Must(template.New("").Funcs(template.FuncMap{
    "avail": avail,
    }).Parse(s))
    exec := func(name string, param interface{}) {
    fmt.Printf("n%s:n ", name)
    if err := t.Execute(os.Stdout, param); err != nil {
    fmt.Println("Error:", err)
    }
    }

    exec("Filled struct", struct {
    Email string
    }{Email: "as@as.com"})
    exec("Empty struct", struct{}{})


    Output (try it on the Go Playground):



    Filled struct:
    Email is: as@as.com
    Empty struct:
    Email is unavailable.





    share|improve this answer















    The recommended way



    First, the recommended way is not to rely on whether a struct field exists. Of course there might be optional parts of the template, but the condition to decide whether to render a part should rely on fields that exist in all cases.



    The issue, and avoiding it using a map



    If the type of the template data is a struct (or a pointer to a struct) and there is no field or method with the given name, the template engine returns an error for that.



    You could easily get rid of this error if you were to use a map, as maps can be indexed with keys they don't contain, and the result of that index expression is the zero value of the value type (and not an error).



    To demonstrate, see this example:



    s := `{{if .Email}}Email is: {{.Email}}{{else}}Email is NOT set.{{end}}`

    t := template.Must(template.New("").Parse(s))
    exec := func(name string, param interface{}) {
    fmt.Printf("n%s:n ", name)
    if err := t.Execute(os.Stdout, param); err != nil {
    fmt.Println("Error:", err)
    }
    }

    exec("Filled map", map[string]interface{}{"Email": "as@as"})
    exec("Empty map", map[string]interface{}{})

    exec("Filled struct", struct {
    Email string
    }{Email: "as@as.com"})
    exec("Empty struct", struct{}{})


    Output (try it on the Go Playground):



    Filled map:
    Email is: as@as
    Empty map:
    Email is NOT set.
    Filled struct:
    Email is: as@as.com
    Empty struct:
    Error: template: :1:5: executing "" at <.Email>: can't evaluate field Email in type struct {}


    Sticking to struct and providing "isset"



    If you must or want to stick to a struct, this "isset" can be implemented and provided, I'll call it avail().



    This implementation uses reflection, and in order to check if the field given by its name exists (is available), the (wrapper) data must also be passed to it:



    func avail(name string, data interface{}) bool {
    v := reflect.ValueOf(data)
    if v.Kind() == reflect.Ptr {
    v = v.Elem()
    }
    if v.Kind() != reflect.Struct {
    return false
    }
    return v.FieldByName(name).IsValid()
    }


    Example using it:



    s := `{{if (avail "Email" .)}}Email is: {{.Email}}{{else}}Email is unavailable.{{end}}`

    t := template.Must(template.New("").Funcs(template.FuncMap{
    "avail": avail,
    }).Parse(s))
    exec := func(name string, param interface{}) {
    fmt.Printf("n%s:n ", name)
    if err := t.Execute(os.Stdout, param); err != nil {
    fmt.Println("Error:", err)
    }
    }

    exec("Filled struct", struct {
    Email string
    }{Email: "as@as.com"})
    exec("Empty struct", struct{}{})


    Output (try it on the Go Playground):



    Filled struct:
    Email is: as@as.com
    Empty struct:
    Email is unavailable.






    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Jun 21 '17 at 17:25

























    answered Jun 21 '17 at 12:29









    iczaicza

    166k25330364




    166k25330364













    • Thanks for the details and the examples!

      – Pascut
      Jun 21 '17 at 12:52



















    • Thanks for the details and the examples!

      – Pascut
      Jun 21 '17 at 12:52

















    Thanks for the details and the examples!

    – Pascut
    Jun 21 '17 at 12:52





    Thanks for the details and the examples!

    – Pascut
    Jun 21 '17 at 12:52













    0














    If you don't send data containing a variable to the template but you use {{ if .Variable }} you will get the error:




    executing "templatename" at <.Variable>: can't evaluate field Variable in type handler.Data




    My solution was to send the "Email" variable as a boolean (false) in order to pass the {{ if .Email }} function check. But this is a short term solution that I don't like.



    I was inspired by: https://stackoverflow.com/a/31527618/1564840. In that example they show different HTML for authenticated and non-authenticated users. You will see that in both cases they send the "Logged" variable. Try removing that variable from the struct and execute the function. You will receive the error that I mentioned above.






    share|improve this answer






























      0














      If you don't send data containing a variable to the template but you use {{ if .Variable }} you will get the error:




      executing "templatename" at <.Variable>: can't evaluate field Variable in type handler.Data




      My solution was to send the "Email" variable as a boolean (false) in order to pass the {{ if .Email }} function check. But this is a short term solution that I don't like.



      I was inspired by: https://stackoverflow.com/a/31527618/1564840. In that example they show different HTML for authenticated and non-authenticated users. You will see that in both cases they send the "Logged" variable. Try removing that variable from the struct and execute the function. You will receive the error that I mentioned above.






      share|improve this answer




























        0












        0








        0







        If you don't send data containing a variable to the template but you use {{ if .Variable }} you will get the error:




        executing "templatename" at <.Variable>: can't evaluate field Variable in type handler.Data




        My solution was to send the "Email" variable as a boolean (false) in order to pass the {{ if .Email }} function check. But this is a short term solution that I don't like.



        I was inspired by: https://stackoverflow.com/a/31527618/1564840. In that example they show different HTML for authenticated and non-authenticated users. You will see that in both cases they send the "Logged" variable. Try removing that variable from the struct and execute the function. You will receive the error that I mentioned above.






        share|improve this answer















        If you don't send data containing a variable to the template but you use {{ if .Variable }} you will get the error:




        executing "templatename" at <.Variable>: can't evaluate field Variable in type handler.Data




        My solution was to send the "Email" variable as a boolean (false) in order to pass the {{ if .Email }} function check. But this is a short term solution that I don't like.



        I was inspired by: https://stackoverflow.com/a/31527618/1564840. In that example they show different HTML for authenticated and non-authenticated users. You will see that in both cases they send the "Logged" variable. Try removing that variable from the struct and execute the function. You will receive the error that I mentioned above.







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Jun 21 '17 at 23:10









        Paul Roub

        32.6k85773




        32.6k85773










        answered Jun 21 '17 at 12:13









        PascutPascut

        1,42021740




        1,42021740






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f44675087%2fgolang-template-variable-isset%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            yLo0ME06HzUxdx4TDjworjKsSGmWG9 CYs,oid4ior
            UZso9,FooyNSELf

            Popular posts from this blog

            Monofisismo

            Angular Downloading a file using contenturl with Basic Authentication

            Olmecas