- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我目前将所有html文件保存在一个平面目录templates/
中,并使用
tmpl := template.Must(template.ParseGlob("templates/*.html"))
components
,
base
等。但是当我这样做时,我的网站就会停止工作。我在想这可能是上面的内容,还是我需要引用模板中的路径?
{{ template "navbar" }}
{{ template "components/navbar" }}
最佳答案
Go's glob不支持子目录中的匹配文件,即不支持**
。
您可以使用第三方库(在github上有很多实现),也可以为子目录的每个“级别”调用filepath.Glob
并将返回的文件名聚合为一个片,然后将该片传递给template.ParseFiles
:
dirs := []string{
"templates/*.html",
"templates/*/*.html",
"templates/*/*/*.html",
// ...
}
files := []string{}
for _, dir := range dirs {
ff, err := filepath.Glob(dir)
if err != nil {
panic(err)
}
files = append(files, ff...)
}
t, err := template.ParseFiles(files...)
if err != nil {
panic(err)
}
// ...
ParseFiles
的工作原理:(强调我的)
ParseFiles creates a new Template and parses the template definitions from the named files. The returned template's name will have the (base) name and (parsed) contents of the first file. There must be at least one file. If an error occurs, parsing stops and the returned *Template is nil.
When parsing multiple files with the same name in different directories, the last one mentioned will be the one that results. For instance, ParseFiles("a/foo", "b/foo") stores "b/foo" as the template named "foo", while "a/foo" is unavailable.
{{ define "<template_name>" }}
操作为每个文件提供唯一的模板名称(并且不要忘记
{{ end }}
来关闭
define
操作)。
templates/foo/header.html
和
templates/bar/header.html
及其内容如下:
templates/foo/header.html
<head><title>Foo Site</title></head>
templates/bar/header.html
<head><title>Bar Site</title></head>
templates/foo/header.html
{{ define "foo/header" }}
<head><title>Foo Site</title></head>
{{ end }}
templates/bar/header.html
{{ define "bar/header" }}
<head><title>Bar Site</title></head>
{{ end }}
t.ExecuteTemplate(w, "foo/header", nil)
直接执行它们,或者通过让其他模板使用
{{ template "bar/header" . }}
操作引用它们来间接执行它们。
关于go - 如何在子目录中加载模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60898254/
我是一名优秀的程序员,十分优秀!