douzhuo6931 2018-05-02 03:51
浏览 25

Golang HTTP /模板变量

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.

  • 写回答

1条回答 默认 最新

  • douyangcheng4965 2018-05-02 04:52
    关注

    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>}}
    
    评论

报告相同问题?

悬赏问题

  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探