Statically initialize a shortcode?

I’m looking for a way to statically initialize a shortcode. What I mean by that is, take for example an image gallery shortcode. This shortcode might show up multiple times on any given page, but it uses a shared JS library that should only be included/initialized once per page.

{{< gallery >}}
  {{< img src="one.jpg" >}}
  {{< img src="two.jpg" >}}
{{< /gallery >}}

Inside the gallery.html shortcode file, I’d like to have some way to tell my global theme to include the required JS file, ideally in the baseof.html file. Something like (this is contrived but just to get an idea):

<section class="gallery">
  {{.Inner}}
</section>

{{ define "one-time-scripts" }}
  <script src="/js/siema.min.js">
  <script>
    new Siema();
  </script>
{{ end }}

I only use define in the example because it seems like blocks are the way to go here, I’m just not sure how to get them to place nicely together.

Importantly:

  • Including multiple gallery shortcodes on a single page should not add multiple <script> tags to the page itself; and
  • the one-time-scripts block should append to whatever the theme has already been provided in that block, be it through theme partials or other shortcodes, but only once in the case of the gallery shortcode (append, just not multiple times).

Is this possible?

Hi,

You could use .HasShortcode to check for the existence of a shortcode.

2 Likes

I had the same issue once and if you are using multiple different shortcodes that won’t need the script you might want to look into .Ordinal or the solution by @brunoamaral.

Thanks for the great answers!

I think I’m going to go the route of .HasShortcode for now, unless I can figure out something even cleaner. It would be ideal if I could encapsulate the entirety of the functionality in the shortcode’s HTML file itself (as opposed to specifying the JS in the footer partial), but it’s not that big of a deal.