transform.XMLEscape

New in v0.121.0

transform.XMLEscape 函數會移除根據 XML 規範定義的不允許的字元,然後將結果進行轉義,以下列 HTML 實體 替換字元:

  • " → "
  • ' → '
  • & → &
  • < → &lt;
  • > → &gt;
  • \t → &#x9;
  • \n → &#xA;
  • \r → &#xD;

例如:

{{ transform.XMLEscape "<p>abc</p>" }} → &lt;p&gt;abc&lt;/p&gt;

在由 Go 的 html/template 套件渲染的模板中使用 transform.XMLEscape 時,應將字串聲明為安全 HTML,以避免重複轉義。例如,在 RSS 模板中:

layouts/_default/rss.xml
<description>{{ .Summary | transform.XMLEscape | safeHTML }}</description>