告诉Golang首先执行哪个模板 [英] Telling Golang which template to execute first

查看:125
本文介绍了告诉Golang首先执行哪个模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在golang有一个包含不同模板的文件夹。主模板是 main.html ,还有一个 footer.html header.html 。页脚和页眉加载了

  {{templatefooter.html。}} 

位于 main.html



这解析文件

 模板,_:= template.ParseGlob(Templates /+ template_name +/*.html )

因为还有其他目录也有不同的文件名。因此,我不想使用 parseFiles



然而,显示的模板总是按字母顺序排列的第一个模板。 footer.html 。如果我将 main.html 重命名为 a.html ,模板将按照我希望的方式显示(如此加载主模板并在其中执行页脚和页眉)。



我找不到任何文档如何告诉golang哪个模板要先使用。有没有办法做到这一点?

知道一个 template.Template 可能(通常是)多个模板的集合。该模板包含关联模板的地图。当使用 template.ParseFiles() template.ParseGlob() ,返回的 template.Template 将指定已解析的第一个模板(来自多个文件)。您可以在这里阅读更多信息: Go模板名称



不使用 模板。 Execute() (基于上述内容将执行第一个解析模板)使用 Template.ExecuteTemplate() 方法,您可以指定要执行的模板,由其名称指定:

  err:= templates.ExecuteTemplate(w,main.html,data)

这将执行名为main.html的模板,无论顺序如何模板文件被解析(或稍后添加到模板集合中)。


I have a folder with different templates in golang. The main template is main.html and there is also a footer.html and header.html. Footer and Header are loaded with

{{template "footer.html" .}} 

in main.html.

I am using this to parse the files

templates, _ := template.ParseGlob("Templates/" + template_name + "/*.html")

because there are other directories with different file names used aswell. So I don't want to use parseFiles.

However, the template that is displayed is always the first one in alphabetical order, e.g. footer.html. If I rename main.html to a.html the template gets displayed the way I want it to (so loading the main template and executing footer and header inside of it).

I couldn't find any documentation how to tell golang which template to use first. Is there a way to do that?

解决方案

Know that a template.Template may be (usually is) a collection of multiple templates. The template contains a map of the associated templates. When using template.ParseFiles() or template.ParseGlob(), the returned template.Template will designate the first template that was parsed (from the multiple files). You can read more about this here: Go template name

Instead of using Template.Execute() (which –based on the above– will execute the first parsed template) use the Template.ExecuteTemplate() method where you can specify which template you want to execute, specified by its name:

err := templates.ExecuteTemplate(w, "main.html", data)

This will execute the template named "main.html" no matter in what order the template files were parsed (or later added to the template collection).

这篇关于告诉Golang首先执行哪个模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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