HUGO

Cannot reach Scratch set from a shortcode

Hi,

Thanks for maintaining hugo. I love it.

Trying to get a flow as suggested by @bep here.

It worked for half an hour and now I cannot reach the Stratch anymore. In my shortcode I add:

{{ $.Page.Scratch.Add "styles" (slice "scss/shortcodes/timeline.scss") }}

In my partial head.html I try to read it like:

{{ if .Page.Scratch.Get "styles" }}
    <div>working πŸ™ŒπŸΏ</div>
{{ else }}
    <div>not working 😒</div>
{{end}}

{{ if .Scratch.Get "styles" }}
    <div>working πŸ™ŒπŸΏ</div>
{{ else }}
    <div>not working 😒</div>
{{end}}

{{ $content := .Content }}  {{/* Need to invoke .Content to render the shortcodes. */}}
{{- if .HasShortcode "timeline" -}}
    <div>working πŸ™ŒπŸΏ</div>
{{ else }}
    <div>not working 😒</div>
{{end}}

{{ with .Scratch.Get "styles" }}
    <div>working πŸ™ŒπŸΏ</div>
    {{ range (. | uniq) }}
        {{ $scssPath := .}}
        {{ $targetCssName := printf "%s.css" . }}
        {{ $options := (dict "targetPath" $targetCssName "outputStyle" "compressed" "enableSourceMap" true) }}
        {{ $style := resources.Get $scssPath | resources.ToCSS $options | resources.Minify | resources.Fingerprint }}
        <link rel="stylesheet" href="{{ $style.RelPermalink }}" >
    {{ end }}
{{ end }}

And I keep getting β€œnot working :cry:”. As mentioned, it was working for a while. Behavior seems to be inconsistent.

How can I get this working? Or is there any better way I can inject a scss that’s required by a shortcode?

The order matters. You need to access .Content (or some of the other page methods that trigger rendering of the content/shortcodes) before you access the scratch variables.

1 Like

Thanks for the fast response and maintaining/improving hugo :heart:

It’s still inconsistent. To reproduce one could add .Content access and than try to access stratch variables, and re-run hugo serve several times. It works maybe 1 out of 10 times.

Side note: {{ if .HasShortcode ".." }} works without any issue but it’s simply bad that the caller is then required to have shortcode names hardcoded, would also be better with some kind of .ShortcodeList where one could iterate…