有没有办法在 if 操作中调用 golang 可重用模板?

问题描述 投票:0回答:1

我想知道是否有任何方法可以使用在

if
条件中调用可重用模板的输出,例如类似这样的事情:

{{ define "test.tmpl" }}SomeExpectedValue{{ end }}
Header
{{/* here \/ */}}
{{- if eq (template "test.tmpl") "SomeExpectedValue" }}
The expected body: {{ template "test.impl" }}.
{{- else }}
Something else.
{{- end }}
Footer

由于可重用模板可以通过

template
操作轻松地在整个模板主体中使用,因此我希望我也可以在
if
条件下使用它。到目前为止,查看 go 模板docs,我无法找到实现此目的的方法。

谢谢!

go go-templates
1个回答
0
投票

模板的输出不能用作模板内的值。您可以使用在评估模板之前传递给

template.Funcs
的附加模板函数来完成您要查找的内容。因此,不要编写
test.tmpl
,而是编写一个返回值的 Go 函数,然后从模板中调用该函数。

© www.soinside.com 2019 - 2024. All rights reserved.