gpt4 book ai didi

go - 变量在包含的模板中不起作用(html/模板)

转载 作者:IT王子 更新时间:2023-10-29 02:05:34 27 4
gpt4 key购买 nike

模板“head”插入“index”模板并使用一个变量{{ .Title }}

Main.go:

package main

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

"github.com/julienschmidt/httprouter"
)

var (
t = template.Must(template.ParseGlob("templates/*.tpl"))
)

type Page struct {
Title string
Desc string
}

func Index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
index := Page{Title: "This is title", Desc: "Desc"}
t.ExecuteTemplate(w, "index", index)
}

func main() {
router := httprouter.New()
router.GET("/", Index)

http.ListenAndServe(":8080", router)
}

索引.tpl:

{{ define "index" }}

<!DOCTYPE html>
<html lang="en">
{{ template "head" }}
<body>
<h1>Main info:</h1>
Title: {{ .Title }}
Desc: {{ .Desc }}
</body>
</html>


{{ end }}

head.tpl:

{{ define "head" }}

<head>
<meta charset="UTF-8">
<title>{{ .Title }}</title>
</head>

{{ end }}

我得到这个 html:

<!DOCTYPE html>
<html lang="en">


<head>
<meta charset="UTF-8">
<title></title>
</head>


<body>
<h1>Main info:</h1>
Title: This is title
Desc: Desc
</body>
</html>

变量 {{ .Title }} 适用于网站正文,但不适用于网站头部。

最佳答案

您必须将变量传递给模板:

{{ template "head" . }}

关于go - 变量在包含的模板中不起作用(html/模板),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28123595/

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