使用模板内的条件

Nic*_*all 9 if-statement go go-templates

在模板中使用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&eacutet&eacute</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}}
Run Code Online (Sandbox Code Playgroud)

在main.go中:

var FuncMap = template.FuncMap{
    "eq": func(a, b interface{}) bool {
        return a == b
    },
}
var templates = template.Must(template.ParseGlob("templates/*.html"))
Run Code Online (Sandbox Code Playgroud)

并在func main()

templates.Funcs(FuncMap)
Run Code Online (Sandbox Code Playgroud)

该程序编译,但我发现添加{{if eq .Active "something"}} class="active"{{end}}(我这里包括的^^)导致程序不再显示任何文本.知道为什么吗?

joc*_*hen 5

我试图将您的代码转换为一个最小的工作示例,我相信您的代码和模板按预期工作。你可以在Go Playground上看到我的代码(并运行它)。

我对出了什么问题的猜测:您是否注意到{{define ...}}仅定义了一个模板以供将来使用。你仍然需要告诉 Go 实际使用这个模板,通过{{ template "header" }}在主模板中使用或类似,或者使用templates.ExecuteTemplate.