What is the best way to call template.ParseFiles() dynamically in Go instead of passing in x number of strings?

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

What is the best way to call template.ParseFiles() dynamically in Go instead of passing in x number of strings?

问题

我想在Go中加载一个文件夹的HTML模板,目前我只能将每个文件的路径作为字符串传递给参数。

示例:

templates = template.Must(template.ParseFiles("../web/html_templates/edit.html","../web/html_mplates/view.html"))

这样可以正常工作。

以下类似的解决方案将不起作用:

templates = template.Must(template.ParseFiles("../web/html_templates/*"))

我想在配置文件中指定我的模板,但目前无法实现。有什么最好的方法可以解决这个问题?

英文:

I want to load a folder of HTML templates in Go and right now I can only pass in each file path as a string in an argument.

Example:

templates = template.Must(template.ParseFiles("../web/html_templates/edit.html","../web/html_mplates/view.html"))

Works fine.

This and similar solutions won't work:

templates = template.Must(template.ParseFiles("../web/html_templates/*"))

I'd like to specify my templates in a config file but I currently can't. What's the best way to go about this?

答案1

得分: 4

使用ParseGlob函数来一次性解析一个文件夹中的HTML模板。

templates = template.Must(template.ParseGlob("../web/html_templates/*.html"))

有关glob语法,请参阅Match函数的文档。

英文:

Use ParseGlob to parse a folder of HTML templates in one API call.

templates = template.Must(template.ParseGlob("../web/html_templates/*.html"))

See the Match function documentation for the glob syntax.

答案2

得分: 3

你可以利用template.ParseFiles是一个可变参数函数的事实:

var templatesFiles []string
// [...]
// 在这里从配置文件或其他来源填充切片
// [...]
templates = template.Must(template.ParseFiles(templatesFiles...))
英文:

You could use the fact that template.ParseFiles is a variadic function :

var templatesFiles []string
// [...]
// Here fill the slice from your config file or any other source
// [...]
templates = template.Must(template.ParseFiles(templatesFiles...))

huangapple
  • 本文由 发表于 2015年9月4日 08:27:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/32387427.html
匿名

发表评论

匿名网友

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

确定