我知道在 Ruby 中可以使用附加参数渲染部分模板,我该如何在 Go 中做到这一点?
我有一个部分模板_partial1.tmpl:
<div>
text1
{{if foo}}
text2
{{end}}
</div>
Run Code Online (Sandbox Code Playgroud)
从父模板中使用它parent.tmpl:
<div>
{{ template "partial1", }} // how do I pass foo param here??
</div>
Run Code Online (Sandbox Code Playgroud)
如何将参数传递foo给部分?
该文档指出该template指令有两种形式:
{{template "name"}}
具有指定名称的模板将以零数据执行。
{{template "name" pipeline}}
执行具有指定名称的模板 ,并将点设置为管道的值。
后者接受管道语句,然后将其值设置dot为执行模板中的值。所以打电话
{{template "partial1" "string1"}}
Run Code Online (Sandbox Code Playgroud)
将在模板中设置{{.}}为。因此,虽然无法在部分中设置名称,但您可以传递参数,它们将出现在. 例子:"string1"partial1foo.
<div>
{{ template "partial1.html" "muh"}} // how do I pass foo param here??
</div>
Run Code Online (Sandbox Code Playgroud)
{{if eq . "muh"}}
blep
{{else}}
moep
{{end}}
Run Code Online (Sandbox Code Playgroud)
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))
}
Run Code Online (Sandbox Code Playgroud)
blep运行此程序将从部分打印模板的内容。更改传递的值将改变此行为。
您还可以分配变量,因此可以在部分中分配.给:foo
{{ $foo := . }}
Run Code Online (Sandbox Code Playgroud)