1
テンプレート内で、これをどのようにすることができますか?golangテンプレートの出力を変数にキャプチャまたは割り当てます
{{$var := template "my-template"}}
私はちょうど"unexpected <template> in operand"
を取得します。
テンプレート内で、これをどのようにすることができますか?golangテンプレートの出力を変数にキャプチャまたは割り当てます
{{$var := template "my-template"}}
私はちょうど"unexpected <template> in operand"
を取得します。
テンプレート実行の結果を取得するための "組み込み"アクションはありませんが、それを行う関数を登録することで実行できます。
関数をTemplate.Funcs()
関数で登録することができます。Template.ExecuteTemplate()
という名前のテンプレートを実行し、ターゲットとしてbytes.Buffer
を使用することができます(テンプレートへの直接テンプレート実行結果)。ここで
完全な例です:
var t *template.Template
func execTempl(name string) (string, error) {
buf := &bytes.Buffer{}
err := t.ExecuteTemplate(buf, name, nil)
return buf.String(), err
}
func main() {
t = template.Must(template.New("").Funcs(template.FuncMap{
"execTempl": execTempl,
}).Parse(tmpl))
if err := t.Execute(os.Stdout, nil); err != nil {
panic(err)
}
}
const tmpl = `{{define "my-template"}}my-template content{{end}}
See result:
{{$var := execTempl "my-template"}}
{{$var}}
`
は出力(Go Playground上でそれを試してみてください):
See result:
my-template content
"my-template"
テンプレートが登録されている関数execTempl()
によって実行され、その結果は次のように返されますa string
これはテンプレート変数$var
に保存されていますが、単純に出力に追加されますが、必要に応じて他の関数に渡すこともできます。
問題は、テンプレートを処理しているgoコードにアクセスできないことです(私はconsul-templateを使用しています) – bitsofinfo