How should I store dynamic data in the Page object? (hugo serve -w)

I wrote a shortcode that uses <script> and <style> tags, and I dont want to apply them in the html every time I call it. Only the first call should add those tags, while subsequent calls shouldnt, as the tags are already included after the first call.

I read about Store and Scratch and that, now, it is aliased. Using it, I wrote:

{{- if not (.Page.Store.Get "myCounter") -}}
<script type="text/javascript" src= '(...)'></script>
<style>(...)</style>
{{- end -}}

{{- .Page.Store.Add "myCounter" 1 -}}

It works properly when using hugo or at the first build of hugo serve -w. However, in subsenquently builds, it break, The.Page.Store value doesnt reset between builds.

For example, during the first build, myCounter starts at 0. When I call the shortcode it adds one. In the next build, myCounter starts at 1, so it doesnt add the tags, and the shortcode breaks. This behavior continues, incrementing myCounter each time, so subsequent builds start with higher values

I dont think its expected behaviour. Shouldnt hugo serve -w act like a watch dog, and running hugo serve for every change? I dont write it as a issue because I think that maybe Scratch had the behaviour I expect. But since it got deprecated, it should be somewhere else.

Therefore, what would be the proper way to write this functionality?

I tried the flags --noHTTPCache and --disableFastRender, same behaviour.

Perhaps it would be easier to write a shortcode that you apply only when you need it, namely once to add the script and style elements?

If I understand your example, you could use the HasShortcode method within the head element.

1 Like

I think it is a good temporary solution. Thank you.

Yeah, I just forgot that idea. For sure, I will do this. Thank you.

1 Like

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.