gpt4 book ai didi

go - 使用传递的参数渲染部分模板

转载 作者:IT王子 更新时间:2023-10-29 00:43:54 25 4
gpt4 key购买 nike

我知道在 Ruby 中可以渲染带有附加参数的部分模板,我如何在 Go 中实现?

我有一个部分模板_partial1.tmpl:

<div>
text1
{{if foo}}
text2
{{end}}
</div>

从父模板 parent.tmpl 使用它:

<div>
{{ template "partial1", }} // how do I pass foo param here??
</div>

如何将参数 foo 传递给 partial?

最佳答案

documentation说明 template 指令有两种形式:

{{template "name"}}
The template with the specified name is executed with nil data.

{{template "name" pipeline}}
The template with the specified name is executed with dot set to the value of the pipeline.

后者接受管道语句,然后将其值设置为执行模板中的 dot 值。所以调用

{{template "partial1" "string1"}}

将在 partial1 模板中将 {{.}} 设置为 "string1"。因此,虽然无法在部分中设置名称 foo,但您可以传递参数,它们将出现在 . 中。示例:

模板.html

<div>
{{ template "partial1.html" "muh"}} // how do I pass foo param here??
</div>

partial1.html

{{if eq . "muh"}}
blep
{{else}}
moep
{{end}}

main.go

import (
"html/template"
"fmt"
"os"
)

func main() {
t,err := template.ParseFiles("template.html", "partial1.html")

if err != nil { panic(err) }

fmt.Println(t.Execute(os.Stdout, nil))
}

运行此程序将从局部打印带有 blep 的模板内容。更改传递的值将改变此行为。

您还可以分配变量,因此可以在部分中将 . 分配给 foo:

{{ $foo := . }}

关于go - 使用传递的参数渲染部分模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36251743/

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