登录
首页 >  Golang >  Go问答

使用结构体或变量值的字段作为模板名称的方法

来源:stackoverflow

时间:2024-03-05 16:39:26 221浏览 收藏

积累知识,胜过积蓄金银!毕竟在Golang开发的过程中,会遇到各种各样的问题,往往都是一些细节知识点还没有掌握好而导致的,因此基础知识点的积累是很重要的。下面本文《使用结构体或变量值的字段作为模板名称的方法》,就带大家讲解一下知识点,若是你对本文感兴趣,或者是想搞懂其中某个知识点,就请你继续往下看吧~

问题内容

我们可以通过 {{define "home"}} 定义模板名称,然后通过 {{template "home"}} 加载到其他(父)模板中。

如何通过变量值 {{template .TemplateName}} 加载模板。还是不可能?


解决方案


不幸的是你不能。

{{template}} 操作的语法:

{{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.

要包含的模板的名称是一个常量字符串,它不是一个管道,管道在执行过程中可能会根据参数而变化。

如果允许的语法是:

{{template pipeline}}

那么你可以使用像 {{template .templname}} 这样的东西,但由于语法只允许常量字符串,所以你不能。

rob 的推理为什么不允许动态模板调用 (source):

我们希望模板语言是可静态分析的,因此模板调用的上下文是清晰的、可检查的和可锁定的。如果调用点是完全动态的,则无法完成此操作。类似地,如果一个模板可以属于多个集合,则其上下文在不同集合之间可能会有所不同,从而需要同时分析所有集合。由于如果您愿意的话,这两个约束都很容易解决,但代价是在更高级别的包中丢失这些静态检查,因此控制基本模板实现中的情况似乎是明智的。如果约束明确,更高级别的包(例如假设的仅 html 包装器)可以更轻松地保证没有解决方法。

替代方案#1:首先执行可包含模板

您可以做的是先执行您想要包含的模板,然后将结果插入到您想要包含的位置。您可以使用特殊类型在插入时不转义内部模板的结果,例如 html 模板中的 html.HTML

请参阅此示例:

func main() {
    t := template.must(template.new("t").parse(t))
    template.must(t.new("t1").parse(t1))

    params := struct {
        name  string
        value interface{}
    }{"t1", nil}
    b := bytes.buffer{}
    t.executetemplate(&b, params.name, nil)
    params.value = template.html(b.string())

    t.execute(os.stdout, params)
}

const t = `
now i will include template with name: {{.name}}
{{.value}}
/html>`

const t1 = `i'm template t1.`

输出:


now i will include template with name: t1
i'm template t1.
/html>

Go Playground 上尝试一下。

模板 t1 的结果以未转义的方式插入。如果您省略 template.html

params.value = b.string()

t1 将被转义插入,如下所示:


now i will include template with name: t1
i'm template <b>t1</b>.
/html>

替代方案 #2:重组模板

您可以重组模板,以免出现想要包含具有不同名称的模板的情况。

示例:您可能想要创建具有 page 模板的页面,如下所示:


    title, headers etc.
    {{template .page}}
    footers

您可以将其重组为如下所示:

header 模板:


    title, headers, etc.

footer 模板:

footers


您的页面模板将包含 headerfooter,如下所示:

{{template "header" .}}
    page content comes here.
{{template "footer" .}}

替代方案 #3:使用 {{if}} 操作和预定义名称

如果您之前知道模板名称并且列表并不详尽,则可以使用 {{if}} 模板操作来包含所需的模板。示例:

{{if eq .Name "page1"}}

    {{template "page1" .}}

{{else if eq .Name "page2"}}

    {{template "page2" .}}
    ...

{{end}}

替代方案#4:修改静态模板文本

这里的想法是,您可以手动修改外部模板的静态文本并插入要包含的内部模板的名称。

这种方法的缺点是插入内部模板的名称后,必须重新解析模板,所以我不推荐这样做。

到这里,我们也就讲完了《使用结构体或变量值的字段作为模板名称的方法》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>