在模板中使用 if 语句真的让我感到困惑。
我正在尝试将 class = "active"
放入使用 golang 模板制作的导航列表中,以执行检测事件选项卡的基本选项卡菜单。
这是我的尝试:
{{define "header"}}
<!DOCTYPE html>
<html>
<head>
<title>Geoprod</title>
{{template "stylesheet" .}}
</head>
<body>
<nav class="navbar" role="navigation">
<div class="navbar-header">
<a{{if eq .Active "accueil"}} class="active"{{end}} href="/">Geoprod</a>
</div>
<div class="navbar-body">
<ul class="navbar-list">
<li{{if eq .Active "societe"}} class="active"{{end}}><a href="/societe">Société</a></li>
<li{{if eq .Active "dossier"}} class="active"{{end}}><a href="/dossier">Dossier</a></li>
<li{{if eq .Active "temps"}} class="active"{{end}}><a href="/temps">Temps</a></li>
<li{{if eq .Active "mails"}} class="active"{{end}}><a href="/mails">Mails</a></li>
</ul>
</div>
</nav>
{{end}}
在 main.go 中:
var FuncMap = template.FuncMap{
"eq": func(a, b interface{}) bool {
return a == b
},
}
var templates = template.Must(template.ParseGlob("templates/*.html"))
在 func main() 中
templates.Funcs(FuncMap)
程序可以编译,但我发现添加了 {{if eq .Active "something"}} class="active"{{end}}
(^^ 我把它包括在这里) 导致程序不再显示任何文本。知道为什么吗?
最佳答案
我尝试将您的代码转换为最小的工作示例,我相信您的代码和模板可以按预期工作。您可以在 Go Playground 上看到我的代码(并运行它) .
我对出了什么问题的猜测:你有没有注意到 {{define ...}}
只定义了一个模板供将来使用。您仍然需要告诉 Go 实际使用此模板,方法是在主模板中使用 {{ template "header"}}
或类似内容,或者使用 templates.ExecuteTemplate
.
关于if-statement - 在模板中使用条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24755509/