Golang:自定义模板“块”功能?

我想知道是否可以使用自定义函数作为 Golang 模板的模板块。下面的代码显示了一个示例。


{{ custom_func . }}

This is content that "custom_func" should do something with.

{{ end }}

用例有点特殊且不标准。基本上,我希望模板作者能够传入大块文本,其中换行符等受到尊重,并将整个文本块传递给函数。我本可以做类似的事情:


{{ custom_func "This is a lot of text\n with many lines etc." }}

但这对模板作者来说不是很友好。最终目标是让他们写出这样的东西:


Author is writing something normal...


{{ note }}

But would like to wrap this content as a "note".


Which when passed to the "note" function, will wrap the content with appropriate divs etc.

{{ end }}

基本上我正在尝试一个实验,看看我是否可以使用纯 go 模板实现类似“markdown/reStructuredText”的内容。现在主要是一个实验。


最终我可能需要为此编写一个合适的 PEG 解析器,但我想先看看这是否可行。


森栏
浏览 177回答 1
1回答

LEATH

函数的字符串参数可以用双引号"或反引号括起来。在模板中用反引号包裹的字符串文字称为原始字符串常量,它们的工作方式类似于Go 源代码中的原始字符串文字:可能包括换行符(并且不能包含转义序列)。因此,如果您对参数使用反引号,则可能会得到您想要的结果。例如a.tmpl:START{{ note `ab\tcd`}}END加载并执行模板的应用程序:t := template.Must(template.New("").Funcs(template.FuncMap{&nbsp; &nbsp; "note": func(s string) string { return "<note>\n" + s + "\n</note>" },}).ParseFiles("a.tmpl"))if err := t.ExecuteTemplate(os.Stdout, "a.tmpl", nil); err != nil {&nbsp; &nbsp; panic(err)}这将输出:START<note>ab\tcd</note>END如果您在 Go 源代码中定义模板,则有点棘手,就像您对模板文本使用反引号一样(因为您想编写多行),您不能将反引号嵌入原始字符串文字中。你必须打破文字,并连接反引号。在 Go 源文件中执行此操作的示例:func main() {&nbsp; &nbsp; t := template.Must(template.New("").Funcs(template.FuncMap{&nbsp; &nbsp; &nbsp; &nbsp; "note": func(s string) string { return "<note>\n" + s + "\n</note>" },&nbsp; &nbsp; }).Parse(src))&nbsp; &nbsp; if err := t.Execute(os.Stdout, nil); err != nil {&nbsp; &nbsp; &nbsp; &nbsp; panic(err)&nbsp; &nbsp; }}const src = `START{{ note ` + "`" + `ab\tcd` + "`" + `}}END`这将输出相同的结果,请在Go Playground上尝试。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go