safe.URL
介紹
Hugo 使用 Go 的 text/template 和 html/template 套件。
text/template
套件實現了資料驅動的範本,用於生成文字輸出;而 html/template
套件則實現了資料驅動的範本,用於生成安全防範程式碼注入的 HTML 輸出。
預設情況下,Hugo 在渲染 HTML 檔案時會使用 html/template
套件。
為了生成避免程式碼注入的安全 HTML 輸出,html/template
套件會在特定情境下對字串進行轉譯。
使用方式
使用 safe.URL
函式來封裝已知的安全 URL 或 URL 子字串。其他不被允許的協議包括:
http:
https:
mailto:
此類型會存在安全風險:封裝的內容應來自可信來源,因為它將在範本輸出中原文包含。
詳情請參閱 Go 文件。
範例
未宣告為安全的情況下:
{{ $href := "irc://irc.freenode.net/#golang" }}
<a href="{{ $href }}">IRC</a>
Hugo 渲染後為:
<a href="#ZgotmplZ">IRC</a>
要將字串宣告為安全:
{{ $href := "irc://irc.freenode.net/#golang" }}
<a href="{{ $href | safeURL }}">IRC</a>
Hugo 渲染後為:
<a href="irc://irc.freenode.net/#golang">IRC</a>