css类基于加载的模板 [英] css class based on loaded template
问题描述
我在我的_base.html模板中有这个引导导航:
I've got this bootstrap nav in my _base.html template like this:
<ul class="nav navbar-nav">
<li><a href="/" class="">Home</a></li>
<li><a href="/blog/">Blog</a></li>
</ul>
使用Golang我要添加
Using Golang I want to add a
class="active"
。
我已阅读 HTML /模板文档和 thisone 等文章,但我看来我必须写一个golang函数添加
I've read the html/template docs and articles like thisone, but it appears to me that I have to write a golang function that adds
class="active"
到每个相应的列表项。但不知何故仍然我认为如果我可以只添加像
to every correspondending corresponding list-item. But somehow still I think it would be cleaner if I could just add something like
<ul>
<li{{ if .template = "index.html" }} class="active"{{ end }}><a href="/">Home</a></li>
<li{{ if .template = "blog.html" }} class="active"{{ end }}><a href="/blog/">Blog</a></li>
</ul>
或类似的东西。我记得Rob Pike说Golang应该为你做所有的计算,但为什么在html / template-package中有一个if语句?
or something like that. I remember Rob Pike saying Golang should be doing all the calculations for you, but why is there an "if" statement in the html/template-package?
推荐答案
我个人经常为这样的任务实施一个小 eq
助手:
I personally often implement a small eq
helper for tasks like that:
var tmpl = template.Must(template.New("").Funcs(template.FuncMap{
"eq": func(a, b interface{}) bool {
return a == b
},
}).ParseGlob("templates/*.html")
示例用法:
<li{{if eq .Active "index"}} class="active"{{end}}><a href="/">Home</a></li>
但是它只用于显示逻辑本身,保持显示逻辑和实际计算分开是一个很好的做法。
But use it only for the display logic itself. It's a good practice to keep the display logic and the real computation apart.
这篇关于css类基于加载的模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!