执行模板会返回一个意外的 <define> 错误

问题描述

在这代码中,我试图设置导航栏,并在每个文件中定义 nav 因为对于某些文件,导航栏将登录注册,但对于某些文件,它将注销或大约.除了这个 login.html 之外,没有任何文件给我错误错误

错误

panic: template: login.html:7: unexpected <define> in command

代码

{{template "base" .}}

{{define "title"}} Log In {{end}}

{{define "body"}}
    {{if .Loggedin}}
        {{define "nav"}}  // this is line 7 which is showing error.
            <div>
                <a href="/about">About</a>
                <a href="/logout">logout</a>
            </div>
        {{end}}
    {{else}}
        <h1> Log In</h1>    
        <p>Login to access your account.</p>
        <hr>
        <form action="/loggedin" method="POST" name="login" id="login">
            <div>
                <label for="email">Email</label>
                <input type="email" name="email",placeholder="Enter your email address" required>
            </div>
            <div>
                <label for="password">Password</label>
                <input type="password" name="password",placeholder="Enter the password" required>
            </div>
            <div>
                <input type="submit" value="Login">
            </div>
        </form>
    {{end}}
{{end}}

解决方法

引用自package doc of text/template,Nested template definitions:

模板定义必须出现在模板的顶层,就像 Go 程序中的全局变量一样。

你不能在另一个模板定义中定义一个模板(这就是你正在做的)。

另请注意,{{define}} 只是定义了一个模板,并不包含/执行它。

要定义和执行模板,请使用 {{block}}

在您的情况下,将模板定义移至顶层,并使用 {{template}} 操作在需要的地方执行它。

如果您需要基于特定条件的不同模板定义,那是不可能的。

可以定义不同的模板(具有不同的名称),并根据条件包含您需要的模板。

另一种选择是将一些数据(条件)传递给模板,并使其根据模板参数(条件)呈现不同的内容,例如使用 {{if}} 操作。

有关更多选项,请参阅相关内容:How to use a field of struct or variable value as template name?