Golang索引模板包括:

huangapple go评论70阅读模式
英文:

Golang index template including

问题

我在我的项目中有两个模板,如下所示:

var indextemplate = template.Must(template.New("").Parse(`<!DOCTYPE html>
<form action="/compare" method="post">
<input type="date" name="from" required>
<input type="submit">
</form>`))

var comparetemplate = template.Must(template.New("").Parse("Hours since {{.From}} are {{.Duration}}"))

我不明白如何组织代码,以便在HTML模板中(包括头部和</html>结尾)只包含这些模板的内容。

我也不太明白最佳实践是如何组织代码,以使模板与处理程序匹配。因为如果我理解正确,你需要在处理程序之外最好编译模板。

英文:

I have two templates in my project like so:

var indextemplate = template.Must(template.New(&quot;&quot;).Parse(`&lt;!DOCTYPE html&gt;
&lt;form action=&quot;/compare&quot; method=&quot;post&quot;&gt;
&lt;input type=&quot;date&quot; name=&quot;from&quot; required&gt;
&lt;input type=&quot;submit&quot;&gt;
&lt;/form&gt;`))

var comparetemplate = template.Must(template.New(&quot;&quot;).Parse(&quot;Hours since {{.From}} are {{.Duration}}&quot;))

I don't understand how to structure the code so I have the HTML template (with a head and &lt;/html&gt; at the end) and just include those templates into the body.

I also don't quite understand what is best practice to structure the code so that the template matches the handler. Since IIUC you need to best compile the template outside the handler.

答案1

得分: 3

你需要知道的是,template.Template 的值可以是多个模板的集合,可以通过其 Template.Templates() 方法获取该集合。

集合中的每个模板都有一个唯一的名称,可以通过该名称进行引用(参见 Template.Name())。还有一个 {{template "name" pipeline}} 操作,可以在一个模板中包含其他模板,这些模板也是集合的一部分。

看看这个例子。我们定义了两个模板:

const tmain = `<html><body>
Some body. Now include the other template:
{{template "content" .}}
</body></html>
`
const tcontent = `I'M THE CONTENT, param passed is: {{.Param}}`

如你所见,tmain 包含了另一个名为 "content" 的模板。你可以使用 Template.New() 方法(强调:方法,不要与 template.New() 函数混淆)创建一个新的关联命名模板,该模板将成为调用该方法的模板的一部分。因此,它们可以相互引用,例如,它们可以相互包含。

让我们看看将这两个模板解析为一个 template.Template 的代码,以便它们可以相互引用(为简洁起见,省略了错误检查):

t := template.Must(template.New("main").Parse(tmain))
t.New("content").Parse(tcontent)

param := struct{ Param string }{"paramvalue"}

if err := t.ExecuteTemplate(os.Stdout, "main", param); err != nil {
	fmt.Println(err)
}

输出结果(在 Go Playground 上尝试):

<html><body>
Some body. Now include the other template:
I'M THE CONTENT, param passed is: paramvalue
</body></html>

替代方案

还要注意,如果你有许多更大的模板,这种方式会变得不太易读和可维护。你应该考虑将模板保存为文件,并且可以使用 template.ParseFiles()template.ParseGlob(),它们都可以一次解析多个文件,并从中构建模板集合,以便它们可以相互引用。模板的名称将是文件的名称。

英文:

What you should know is that a value of template.Template can be a collection of multiple templates, see its Template.Templates() method which returns this collection.

Each template in the collection has a unique name that it can be referred to by (see Template.Name()). And there is a {{template &quot;name&quot; pipeline}} action, and using that you can include other templates in a template, another template which is part of the collection.

See this example. Let's define 2 templates:

const tmain = `&lt;html&gt;&lt;body&gt;
Some body. Now include the other template:
{{template &quot;content&quot; .}}
&lt;/body&gt;&lt;/html&gt;
`
const tcontent = `I&#39;M THE CONTENT, param passed is: {{.Param}}`

As you can see, tmain includes another template named &quot;content&quot;. You can use the Template.New() method (stressing: method, not to be confused with the func template.New() ) to create a new associated, named template that will be part of the template whose method you're calling. As a result, they can refer to each other, e.g. they can include each other.

Let's see code that parses these 2 templates into one template.Template so they can refer to each other (error check omitted for brevity):

t := template.Must(template.New(&quot;main&quot;).Parse(tmain))
t.New(&quot;content&quot;).Parse(tcontent)

param := struct{ Param string }{&quot;paramvalue&quot;}

if err := t.ExecuteTemplate(os.Stdout, &quot;main&quot;, param); err != nil {
	fmt.Println(err)
}

Output (try it on the Go Playground):

&lt;html&gt;&lt;body&gt;
Some body. Now include the other template:
I&#39;M THE CONTENT, param passed is: paramvalue
&lt;/body&gt;&lt;/html&gt;

Alternative

Also note that if you have many and bigger templates, this becomes less readable and maintainable. You should consider saving your templates as files, and you can use template.ParseFiles() and template.ParseGlob(), both which can parse multiple files at once and they build the template collection from them, so they can refer to each other. The names of the templates will be the names of the files.

huangapple
  • 本文由 发表于 2015年12月3日 14:42:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/34059404.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定