DRYer shortcodes

Hi,

So, I have a shortcode that is called multiple times per page/ post. Inside the shortcode is a script that only needs to be rendered in HTML on the first instance of the shortcode. Does Hugo have a function for that? “Run the following HTML only once”?

Best Regards,
Jonathan Clarke

Sure, here you go: .HasShortcode.

Thanks, @regis! Funny you commented, because I was just reading your excellent blog post on Scratch.

1 Like

Hard to find examples of .HasShortcode, so I’m trying this:

{{ if not ( .HasShortcode "ctas" ) }}
<script>
</script>
{{ end }}

But unfortunately I’m getting this error:

Building sites … ERROR 2018/10/24 10:01:01 error processing shortcode "shortcodes/ctas.html" for page "posts/test-page.md": template: shortcodes/ctas.html:1:12: executing "shortcodes/ctas.html" at <.HasShortcode>: can't evaluate field HasShortcode in type *hugolib.ShortcodeWithPage
Total in 199 ms
Error: Error building site: logged 1 error(s)

No doubt I’m using it incorrectly. Any further pointers?

Can you post what you are actually trying to do or post a link to your repo, maybe using a shortcode might not be the best option.

Solved this by moving code to single.html rather than the shortcode file. I had some help from @julianoaklein!

Right from the doc:

You can check if a specific shortcode is used on a page by calling .HasShortcode in that page template

I’m teasing, happens to me all the time :wink:

2 Likes