gohugoio / hugo

The world’s fastest framework for building websites.
https://gohugo.io
Apache License 2.0
75.38k stars 7.49k forks source link

Method on Page to force content rendering #11897

Closed jmooring closed 9 months ago

jmooring commented 9 months ago

Something like this within the head element of a template will not work because .Content has not been evaluated:

{{ if .Page.Store.Get "hasMermaid" }}
  <script type="module">
    import mermaid from 'https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.esm.min.mjs';
    mermaid.initialize({ startOnLoad: true });
  </script>
{{ end }}

So we do something like this instead:

{{ $noop := .Content }}
{{ if .Page.Store.Get "hasMermaid" }}
  <script type="module">
    import mermaid from 'https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.esm.min.mjs';
    mermaid.initialize({ startOnLoad: true });
  </script>
{{ end }}

Instead of Content you can also invoke FuzzyWordCount, Len, Plain, PlainWords, ReadingTime, Summary, Truncated, or WordCount.

Although {{ $noop := .OneOfTheAbove }} makes sense to me, it is not intuitive to new or casual users.

I don't have any great suggestions at the moment, so maybe what we have is fine.

bep commented 9 months ago

I'm not sure. When passing state around with scratch you're already in advanced territory and need to understand how things fits together.

{{/* Prepare content. */}}
{{ $content := .Content }}
{{/* Check if mermaid was used during the content rendering above. */}}
{{ if .Page.Store.Get "hasMermaid" }}
  <script type="module">
    import mermaid from 'https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.esm.min.mjs';
    mermaid.initialize({ startOnLoad: true });
  </script>
{{ end }}
{{/* Print content. */}}
{{ $content }}

The above could even be rewritten to:

{{  with .Content }}
{{/* Check if mermaid was used during the content rendering above. */}}
   {{ if $.Page.Store.Get "hasMermaid" }}
  <script type="module">
    import mermaid from 'https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.esm.min.mjs';
    mermaid.initialize({ startOnLoad: true });
  </script>
   {{ end }}
   {{/* Print content. */}}
   {{ .}}
{{ end }}
jmooring commented 9 months ago

Yeah, this just need to be documented. See https://github.com/gohugoio/hugoDocs/issues/2402.

github-actions[bot] commented 8 months ago

This issue has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.