为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

Go
森栏 2023-03-07 15:23:31
我想知道是否可以使用自定义函数作为 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 解析器,但我想先看看这是否可行。
查看完整描述

1 回答

?
LEATH

TA贡献1936条经验 获得超6个赞

函数的字符串参数可以用双引号"或反引号括起来。

在模板中用反引号包裹的字符串文字称为原始字符串常量,它们的工作方式类似于Go 源代码中的原始字符串文字:可能包括换行符(并且不能包含转义序列)。

因此,如果您对参数使用反引号,则可能会得到您想要的结果。

例如a.tmpl

START

{{ note `a

b\t

c

d`}}

END

加载并执行模板的应用程序:


t := template.Must(template.New("").Funcs(template.FuncMap{

    "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 {

    panic(err)

}

这将输出:


START

<note>

a

b\t

c

d

</note>

END

如果您在 Go 源代码中定义模板,则有点棘手,就像您对模板文本使用反引号一样(因为您想编写多行),您不能将反引号嵌入原始字符串文字中。你必须打破文字,并连接反引号。


在 Go 源文件中执行此操作的示例:


func main() {

    t := template.Must(template.New("").Funcs(template.FuncMap{

        "note": func(s string) string { return "<note>\n" + s + "\n</note>" },

    }).Parse(src))


    if err := t.Execute(os.Stdout, nil); err != nil {

        panic(err)

    }

}


const src = `START

{{ note ` + "`" + `a

b\t

c

d` + "`" + `}}

END

`

这将输出相同的结果,请在Go Playground上尝试。



查看完整回答
反对 回复 2023-03-07
  • 1 回答
  • 0 关注
  • 80 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信