亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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”的內容?,F在主要是一個實驗。最終我可能需要為此編寫一個合適的 PEG 解析器,但我想先看看這是否可行。
查看完整描述

1 回答

?
LEATH

TA貢獻1936條經驗 獲得超7個贊

函數的字符串參數可以用雙引號"或反引號括起來。

在模板中用反引號包裹的字符串文字稱為原始字符串常量,它們的工作方式類似于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 關注
  • 123 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號