Use conditional for css style with shortcode

I use the following code to apply specific css style for a given shortcode:

{{- if .HasShortcode "blockquote" -}}
{{ $block := resources.Get "css/conditional/shortcodes/blockquote.css" | minify | fingerprint }}
<link rel="stylesheet" href="{{ $block.Permalink }}" media="all">
{{ end }}

2 questions:

  • is it the best way to do it?
  • if I want to use the same condition for 2 different shortcodes -(ie. blockquote or quote) can I modify the code with {{ if .HasShortcode "blockquote" or "quote" }} and what is the correct syntax

Thank you

1 Like

{{ if or (.HasShortcode ā€œs1ā€) (.HasShortcode ā€œs2ā€) }}

Thanks a lot.
If I may, for the first question, is it the best way?

Iā€™m not sure. The thing is, in most situations, packaging all of the CSS to cover all scenarios (shortcodes etc.) and include them in every page is the simplest and good enough.

The problem with your approach is that your template needs to know about the shortcode.

What you could consider doing instead is having the shortcode telling the template what it needs, e.g. in the shortcode template:

{{ $stylesNeeded := slice "css/conditional/shortcodes/blockquote.css" "css/conditional/shortcodes/foo.css" }}
{{ $.Page.Scratch.Add "styles" $stylesNeeded }}

Then in your single.html template (or something):

{{/* Need to invoke .Content to render the shortcodes. */}}
{{ $content := .Content }}
{{ with .Scratch.Get "styles" }}
{{ range (. | uniq) }}
// Get the resource and create a link
{{ end }}
{{ end }}

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