Changing a site Param's value in a shortcode

Is it possible to change a site param’s setting in a shortcode? I need to call a script only in pages that contain videos, and the way I do this right now is by including a hasvideo param in each page’s front matter, set by default to false in the default article archetype, and including a conditional call to the scripts using that param in the footer script partial.

1. Front matter:

---
title: "Curabitur viverra, neque nec porttitor semper, sapien massa euismod erat, eget rutrum eros ligula sed nibh."
categories: ["A"]
tags: ["a", "b", "c"]
...
hasvideo: true
---

2. Footer conditional:

<!-- Adds js for video on pages where it's needed -->

{{ with .Params.hasvideo }} {{ if . }}
<link rel="stylesheet" href="/vidstack/styles/base.css" />
<!-- the following styles are optional - remove to go headless
<link
  rel="stylesheet"
  href="https://cdn.jsdelivr.net/npm/vidstack/styles/ui/buttons.min.css"
/>
<link
  rel="stylesheet"
  href="https://cdn.jsdelivr.net/npm/vidstack/styles/ui/sliders.min.css"
/>  -->
<script type="module" src="/vidstack/dist/cdn/prod.js"></script>
{{ end }} {{ end }}

But it would be nice not to have to remember to override hasvideo’s value every time I add a video to a page. And since any page including video content does so by using a shortcode, I thought I would try to set the value of the hasvideo site param to true at the start of the video.html shortcode. But {{ .Set site.Params.hasvideo "true" }} triggers an error.

Is it actually possible to do this?

https://gohugo.io/templates/shortcode-templates/#checking-for-existence

1 Like

Perfect. Thanks! I hadn’t spotted that or even thought of doing it that way round.

Though .HasShortcode solves my issue, just out of curiosity, is it actually possible to do what I was wanting to do, i.e. change a site param in a shortcode?

Site and page parameters are immutable; they cannot be changed once set. You could set a page level Scratch instead of using .HasShortcode, but I wouldn’t.

Good to know. Your solution solves it beautifully and I’ll use it to lighten some of the css used only in other shortcodes, too (contact form, toggles, etc.)

1 Like

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