gpt4 book ai didi

go - 更新嵌套模板 Golang

转载 作者:IT王子 更新时间:2023-10-29 02:00:58 24 4
gpt4 key购买 nike

我正在尝试动态更改内容。但内容保持不变。似乎要获取第一场比赛。不管模板是什么。即使使用硬编码文件名也不起作用。代码按预期工作,但内容无法更改。

主要布局

{{define "layout"}}
<html>
<body>
{{ template "content" }}
</body>
</html>
{{end}}

子模板1

{{ define "content" }}

<h1 style="color: red;">Page 1!</h1>

{{ end }}

子模板2

{{ define "content" }}

<h1 style="color: blue;">Page 2!</h1>

{{ end }}

Go 代码

package main

import (
"html/template"
"net/http"
"strings"
)

var tpl *template.Template

func init() {
tpl = template.Must(template.ParseGlob("templates/*.gohtml"))
}

func main() {
http.HandleFunc("/", index)
http.ListenAndServe(":8080", nil)
}

func index(w http.ResponseWriter, r *http.Request) {

path := strings.Trim(r.URL.Path, "/")
switch path {
case "":
path = ("index.gohtml")
default:
path = (path + ".gohtml")
}

err := tpl.ExecuteTemplate(w, "layout", path)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}

我也曾尝试在执行之前先解析文件,但没有成功。我做错了什么?

最佳答案

我认为在解析模板后调整路径为时已晚。

可以使用 AddParseTree 方法(虽然我不确定这里是否是最优雅的解决方案):

AddParseTree adds parse tree for template with given name and associates it with t. If the template does not already exist, it will create a new one. If the template does exist, it will be replaced.

适用于您的情况,根据您将解析相关模板文件(子模板1或2)的条件,然后使用AddParseTree将其添加到tpl,在你执行它之前。

关于go - 更新嵌套模板 Golang,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54618088/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com