Use shortcode within definition of shortcode
Asked Answered
D

2

15

How can I reuse a shortcode in Hugo within another shortcode?

I only found a way to nest shortcodes within markdown but what I want to do is to reuse a shortcode within the definition of another shortcode.

Dichromic answered 28/3, 2019 at 15:45 Comment(0)
W
6

No not in the definition, but you can use nested Shortcodes.

The nested approach is the official one (as discussed here):

Nested Shortcodes

You can call shortcodes within other shortcodes by creating your own templates that leverage the .Parent variable.
.Parent allows you to check the context in which the shortcode is being called.
See Shortcode templates.

See an illustration here: this is a workaround, and not one shortcode using another.

Weltanschauung answered 31/3, 2019 at 12:56 Comment(0)
H
3

You can do it with partials as a workaround: You can outsource your reusable shortcode into a partial and call that inside your shortcode as often as you want. For the sake of an example, I'm going to write my own string to lowercase function:

layout/partials/string-to-lower.html:

{{- $stringOriginal := . -}}
{{- $stringLower := $stringOriginal | lower -}}
{{- return $stringLower -}}

layout/shortcodes/some-shortcode.html:

{{- $myString := "TeST" -}}
{{- partial "string-to-lower" $myString -}}

{{< some-shortcode >}} will then print test in your content.


If you want to use your shortcode not only in other shortcodes, but also in your content, then you can work with a wrapper shortcode for your outsourced shortcode (partial):

layout/partials/string-to-lower.html (the outsourced code):

{{- $stringOriginal := . -}}
{{- $stringLower := $stringOriginal | lower -}}
{{- return $stringLower -}}

layout/shortcodes/string-to-lower.html (the wrapper):

{{- with .Get 0 -}}
    {{- partial "string-to-lower" . -}}
{{- end -}}

Then you can use {{< string-to-lower "TeST" >}} in your content or {{- partial "string-to-lower" "TeST" -}} in your templates to print test.

Holdall answered 14/8, 2022 at 17:13 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.