HasShortcode

範例

假設使用 Plotly 繪製圖表:

內容頁面 (Markdown)

{{< plotly >}}
{
  "data": [
    {
      "x": ["giraffes", "orangutans", "monkeys"],
      "y": [20, 14, 23],
      "type": "bar"
    }
  ],
}
{{< /plotly >}}

Shortcode 定義 (HTML)

{{ $id := printf "plotly-%02d" .Ordinal }}
<div id="{{ $id }}"></div>
<script>
  Plotly.newPlot(document.getElementById({{ $id }}), {{ .Inner | safeJS }});
</script>

在模板中條件加載資源

如果某頁面使用了 plotly shortcode,則只需針對該頁面載入對應的 JavaScript:

<head>
  ...
  {{ if .HasShortcode "plotly" }}
    <script src="https://cdn.plot.ly/plotly-2.28.0.min.js"></script>
  {{ end }}
  ...
</head>

這種方法有效地避免了為不需要的頁面載入多餘的資源,提高了頁面性能。