【问题标题】:executing a template returns an unexpected <define> error执行模板返回意外的 <define> 错误
【发布时间】:2021-10-05 23:13:21
【问题描述】:

在这段代码中,我试图设置导航栏,并在每个文件中定义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}}

【问题讨论】:

    标签: go go-templates


    【解决方案1】:

    引用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?

    【讨论】:

      猜你喜欢
      • 2016-08-10
      • 2022-11-21
      • 2019-09-10
      • 2021-04-16
      • 2015-05-09
      • 2015-08-23
      • 1970-01-01
      • 1970-01-01
      • 2015-11-10
      相关资源
      最近更新 更多