简体   繁体   中英

Golang http/template variable

I have a variable in a template called $active and the idea is to check against it to make a navrbar button active or not. I have defined a header where the logic is taking place but I am trying to define $active on the html file being called by my Execute function. The issue is that the header is read first so any variables defined in the body files is too late to affect the logic. From the header:

{{ $a := mkSlice "SiteTester" "/sitetester-add/" }}
{{ $b := mkSlice "Index" "/" }}
{{ $nav := mkSlice $a $b }}
                <ul class="nav navbar-nav">
                    {{range $nav}}
                    <li{{if eq $active (index . 0) }} class="active"{{end}}><a href="{{index . 1}}">{{index . 0}}</a></li>
                    {{end}}
                </ul>

I've even been trying to make a separate snippit just to handle the variable assignment:

{{define "indexpreload"}}
{{$active := "Index"}}
{{end}} 

And call it first in the parsed .html:

    {{template "indexpreload" .}}    
    {{template "header" .}}

    <h3 class="section-banner"><strong>Welcome</strong></h3>
    <hr class="divider">
    <div class="form-group col-md-4 text-left"></div>
    <div class="form-group col-md-4 text-left">
        <br><br>
        <p>Content content content</p>

    </div>

    {{template "footer" .}}

I would appreciate any ideas of how to assign the variable before the header is run? I'd love to keep this login within the template so I don't have to worry about passing a variable from my program.

Do you ever find that the act of writing out your question clarifies the issue in your mind so you answer it yourself shortly after? That happened here when I realized I needed to figure out how to pass local variables between nested templates. For anyone seeing this hoping for help with the same issue, it's as simple as

{{template "<name>" $<variable name>}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM