How to identify in a shortcode if it's rendered on a list template or in a single template?

Hi everyone,

I have a hugo site where the content files are generated in the content folder based on a script.
The content file structure is like this:


Inside every service md file it is used a shortcode:
{{< service-shortcode >}}

There is the graphs/list.html layout where a partial is used to render the content of the pages:

    {{ range $pages }}
      {{ partial "li-graphs.html" . }}
    {{ end }}

The li-graphs.html file renders the content:

<div> {{ .Content }} </div>
    <a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a>

The result is a page where every service (md file) is rendered in a list template and when you click on the service title (a href) it will navigate to a default single template displaying the content of the service.

I want to add an additional html element in the shortcode if the shortcode is displayed in a single template.
How can I identify in the shortcode if it’s rendered in the list template or in the single template?
Smth like:

{{ if isSingleTemplate }}
<h1> Single template </h1>
{{ end }}

<div> Shortcode content</div>

I tried using the page variables: .isPage, .isNode, .isSection, etc and it doesn’t work.
And I also tried with .Page.Permalink but it gives the same url on the list and single templates.
Is there another way of doing this using hugo’s features?

You cannot.

I would either:

  • Add the HTML element before or after .Content in the template, OR

  • Handle this with CSS

1 Like

Thanks @jmooring for the reply.

Isn’t there a way to pass a variable to the content file from the list or single Html template and in the content file to access it and pass it forward to the shortcode?

Or can’t a global variable be set in config (template = “list”) and change it in single and list template and in the shortcode use it for conditional rendering?

Write two shortcodes, one with the extra <h1> Single template </h1>
I’ve called them “shortcodenoh1” and “shortcodewithh1”

Add the extra html to the {{< shortcodewithh1 >}}

In your script generated content there will only be the orginal {{< shortcodenoh1 >}}
So, the idea is (I tested switching out a hero image shortcode and it worked) to swap the shortcodes out only on the single template to render the extra html.

{{- .RawContent | replaceRE {{<\s?(shortcodenoh1) “{{< shortcodewithh1” | markdownify }}

(I’m no regex expert!)

1 Like

Yes, with .Scratch or .Store, but that will not help you. A page’s .Content is rendered once per output format, and once rendered is immutable.

No. Configuration parameters are immutable. And even if could change them, it would not help you, because a page’s .Content is rendered once per output format, and once rendered is immutable.

1 Like

I just figured out how to do this.