我想知道是否有任何方法可以使用在 if
条件中调用可重用模板的输出,例如类似这样的事情:
{{ define "test.tmpl" }}SomeExpectedValue{{ end }} Header {{/* here / */}} {{- if eq (template "test.tmpl") "SomeExpectedValue" }} The expected body: {{ template "test.tmpl" }}. {{- else }} Something else. {{- end }} Footer
由于可以通过 template
操作在整个模板正文中轻松使用可重用模板,因此我希望我也可以在 if
条件中使用它。到目前为止,查看 go 模板文档,我无法找到实现此目的的方法。
模板的输出不能用作模板内的值。您正在寻找的内容可以使用在评估模板之前传递给 template.Funcs
的附加模板函数来完成。因此,不要编写 test.tmpl
,而是编写一个返回值的 Go 函数,并从模板中调用该函数。