safe.CSS
介紹
Hugo 使用 Go 的 text/template 和 html/template 套件。
text/template
套件實現了資料驅動的範本,用於生成文字輸出;而 html/template
套件則實現了資料驅動的範本,用於生成安全防範程式碼注入的 HTML 輸出。
預設情況下,Hugo 在渲染 HTML 檔案時會使用 html/template
套件。
為了生成避免程式碼注入的安全 HTML 輸出,html/template
套件會在特定情境下對字串進行轉譯。
使用方式
使用 safe.CSS
函式來封裝已知安全的內容,適用於:
- CSS3 樣式表生產,例如
p { color: purple }
。 - CSS3 規則生產,例如
a[href=~"https:"].foo#bar
。 - CSS3 陳述式生產,例如
color: red; margin: 2px
。 - CSS3 值生產,例如
rgba(0, 0, 255, 127)
。
使用此類型會存在安全風險:封裝的內容應來自可信來源,因為它將在範本輸出中原文包含。
詳情請參閱 Go 文件。
範例
未宣告為安全的情況下:
{{ $style := "color: red;" }}
<p style="{{ $style }}">foo</p>
Hugo 渲染後為:
<p style="ZgotmplZ">foo</p>
要將字串宣告為安全:
{{ $style := "color: red;" }}
<p style="{{ $style | safeCSS }}">foo</p>
Hugo 渲染後為:
<p style="color: red;">foo</p>