微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Golang 模板变量

如何解决Golang 模板变量

这是我第一次尝试用 Go 做前端。 我有这个模板:

{{define "index"}}{{template "_header.html"}}
{{template "_message.html"}}
<div>Page Index</div>
<div>Welcome {{.Title}}</div>    
{{template "_footer.html"}}     
{{end}}

{{.Title}} 按预期工作的地方。

但是当我尝试在包含文件 {template "_header.html"} 中使用它时,它失败了。

{{define "_header.html"}}<!DOCTYPE html>
<html lang="en">
    <head>
        <Meta charset="utf-8">
        <Meta name="viewport" content="width=device-width,initial-scale=1">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css"/>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap-theme.min.css"/>
        <link rel="stylesheet" href="./css/css.css"/>
        <title>{{.Title}}</title>
    </head><body>{{end}} 

现在 <title> 标签为空。

有什么建议吗?

解决方法

根据模板文档,使用 {{ template "name" }} 将 nil 数据传递给您的模板。因此,没有要渲染到 {{ .Title }} 中的数据。您需要使用 {{ template "name" pipeline }} 将数据传递到包含的模板中。

在您的情况下,{{ template "_header.html" . }} 应该可以解决问题,将当前数据对象传递到您包含的模板中。

template documentation here

{{template "name"}}
    The template with the specified name is executed with nil data.

{{template "name" pipeline}}
    The template with the specified name is executed with dot set
    to the value of the pipeline.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。