检测Go模板模块是否存在的方法

时间:2024-02-19

浏览:303

作者:佚名

学习知识要善于思考,思考,再思考!今天golang学习网小编就给大家带来《检测Go模板模块是否存在的方法》,以下内容主要包含等知识点,如果你正在学习或准备学习Golang,就都不要错过本文啦~让我们一起来看看吧,能帮助到你就更好了!

问题内容

我正在使用带有内置 html 模板引擎的 go 1.19。有没有办法测试某个块是否在特定模板文件中定义?

具体来说,我想在 go html 模板中实现可选的标头条目。

我有一个通用布局模板,其中包含呈现时的内容模板。

我想实现如下...

目前,<meta name="description" content="{{block "description" .}}{{end}}"> 会导致空的描述标记。如果标签中没有任何内容,我希望根本没有该标签。

有什么想法吗?

layout.gohtml(简化)[更新]

<html>
<head>
    <title>{{block "title" .}}the title{{end}}</title>
    {{if .renderdescription}}
        <meta name="description" content="{{template "description"}}">
    {{end}
</head>
<body>
    <header></header>
    {{template "content" .}}
    <footer></footer>
</body>
</html>

content1.gohtml

{{define "title"}}the 2ho network{{end}}
{{define "description"}}an options description{{end}}
{{define "content"}}
    vestibulum ante ipsum primis in faucibus...
{{end}}

content2.gohtml

{{define "title"}}The 2hO Network{{end}}
{{define "content"}}
    Vestibulum ante ipsum primis in faucibus...
{{end}}


正确答案


模板被设计为可静态分析。这意味着如果您没有 description 模板,则在解析模板时会出现错误。

而是使用 {{if}} 操作来检查是否需要呈现 description 模板。 description 模板可能为空。

例如:

{{if .renderdescription}}
    {{template "description"}}
{{end}}

{{define "description"}}description content{{end}}

如果您必须在很多地方检查 .renderdescription,您也可以将检查({{if}} 操作)移至模板中,这样您就可以无条件使用 {{template}} (但您仍然必须提供包含条件的管道):

{{template "description" .}}


{{define "description"}}
    {{if .renderDescription}}
        description content
    {{end}}
{{end}}

注释:

{{block}} 操作不是包含模板,而是定义并包含模板。要包含在其他地方定义的模板,请使用 {{template}}。

您还必须更改模板结构。不要使用嵌入“内容”的“框架”模板,而是定义“页眉”和“页脚”模板,并让每个页面都有自己的模板,其中包括“页眉”、内容和“页脚”。

到这里,我们也就讲完了《检测Go模板模块是否存在的方法》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

本文内容来源于互联网,如有侵权请联系删除。

相关文章

更多

热门专题

更多
首页