tmpl.Execute和子文件golang [英] tmpl.Execute and sub-file golang

查看:195
本文介绍了tmpl.Execute和子文件golang的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要帮助。
我需要使用html / template的标记( {{。Title}} ,例如)在子文件中(article.html,例如在我的文本中):

  // ... 
类型页面结构{
测试字符串
}

类型新闻结构{
Page
标题字符串
}

func main(){
t,_:= template.ParseFiles(filepath +core.tmpl,filepath +article.tmpl)
p:=& News {
标题:TITLE,
Page:页面{
测试:TITLE,
},
}
t.Execute(wr,p)
}

core.tmpl

  {{templatearticle}} 

$ b $ p $ article.tmpl 中的代码:

  {{definearticle}} 
{{.Title}}< br>< br>
{{.Page.Test}}
{{end}}


解决方案

在您的 core.tmpl 中,您必须使用

  {{templatearticle。}} 

如果您没有指定最后,模板将以 nil 数据执行。指定会将的值传递给被调用的模板。



text / template 引用包装文件,操作部分:

  {{template name}} 
具有指定名称的模板以零数据执行。

{{templatenamepipeline}}
具有指定名称的模板以点设置
执行到管道的值。


I need help. I need to use "html/template"'s marking ({{.Title}}, example) in sub-files("article.html", example in my text):

// ...
type Page struct {
    Test string
}

type News struct {
    Page
    Title string
}

func main() {
    t, _ := template.ParseFiles(filepath+"core.tmpl", filepath+"article.tmpl")
    p := &News{
        Title: "TITLE",
        Page: Page{
            Test: "TITLE",
        },
    }
    t.Execute(wr, p)
}

Code in core.tmpl:

{{template "article"}}

Code in article.tmpl:

{{define "article"}}
{{.Title}}<br><br>
{{.Page.Test}}
{{end}}

解决方案

In your core.tmpl you have to use

{{template "article" .}}

If you don't specify the . at the end, the template will be executed with nil data. Specifying the . will pass the value of . to the invoked template.

Quoting from the text/template package documentation, Actions section:

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

这篇关于tmpl.Execute和子文件golang的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆