.HasShortcode check with the shortcode inside a headless bundle

I’ve got a shortcode that loads Javascript in a footer.html partial, inside a .HasShortcode check. This works fine with ordinary pages.

I’m creating a one-page theme that builds index.html by ranging through content from a headless bundle. Some of the pages in that bundle, but not the content of index.html itself, call the shortcode in question.

In this instance .HasShortcode doesn’t return the expected JS block. I guess that’s because the page itself doesn’t have the shortcode, but rather the page that is looped over?

Is there a way around this, or something I’m missing?

I don’t have a public repo available but here is the relevant setup:

footer.html

{{ if .HasShortcode "shortcode" }}
{{ block "shortcode-js" . }}{{ end }}
{{ end }}

shortcode.html

{{ define "shortcode-js" }}
<!-- code -->
{{ end }}

<!-- rest of the shortcode -->

index.html

{{ $sections := site.GetPage "home_sections" }}
{{ range sort $sections.Pages "File.Path" }}

<!-- stuff -->
  
{{ end }}

Content directory

.
├── home_sections
│   ├── _index.md
│   ├── section1.md
│   ├── section2.md
│   └── section3.md
└── _index.md

_index.md in home_sections

---
title: "Home Sections"
_build:
  list: 'local'
  publishResources: false
  render: 'never'
---

The shortcode is in section1.md

Thanks!

I came across this limitiation, too when trying to generate a print output for the whole project.

That’s the reasion why in my solution, I am doing it all by hand:

  • in the shortcode I do .Store.Set to set a marker flag
  • in the range I loop over all pages and transfer the marker flag of the subpages to their parent using .Store.Get and Store.Set
{{ $hasShortCodeFoo := false }}
{{ range site.RegularPages }}  {{/* Or some other page collection */}}
  {{ $hasShortCodeFoo = or $hasShortCodeFoo (.HasShortcode "foo") }}
{{ end }}

{{ if $hasShortCodeFoo }}
  DO SOMETHING
{{ end }}

Thanks @jmooring, this gave me something to think about and it’s 90% of the way there.

I can get the <script> tag to print inside the if statement now and it’s functional.

One question: Is there any way to send this output to the block defined in the footer.html partial? Hugo won’t let me define a block inside the main block, and if I try to define it outside, the variable check fails.

Can this work or am I asking for something that isn’t possible?

Sorry, but I am having a difficult time understanding the template/base/block/partial structure of your site.