Positional shortcodes with two or more parameters?

Hello there,

I am trying to figure out shortcodes as per the documentation at https://gohugo.io/templates/shortcode-templates/#custom-shortcode-examples

Can anyone give me an example of how to do a positional parametered shortcode with two parameters? (if it is possible)

The documentation says that we can use either positional or named parameters…but gives no example or explanation for two patameterd positional…it just says, it is best to use named parameters…(which to me implies that you can use a positonal method even though it’s not the best way)…

Thanks for any thoughts

When doing positional, just use the next index for your second arg.

{{< myshortcode first second >}}
{{ index .Params 0 }} //pulls first
{{ index .Params 1 }} //pulls second

As for which is “better” I guess it depends how good your memory is. For me it’s six of one and half dozen of the other, in that positional keeps your markdown brief but you have to remember what position holds what param, whereas, named is more precise and the names can come in any order, but, I can never remember the names I decided on!


Like the example states:

<div class="embed video-player">
<iframe class="youtube-player" type="text/html" width="640" height="385" src="http://www.youtube.com/embed/{{ index .Params 0 }}" allowfullscreen frameborder="0">

To access each param you would use {{index .Params 0}} if you add another param it would be: {{index .Params 1}}

I tend to prefer named params but that is basically how it works.

Here is one with slighty different syntax. Say it’s named myshortcode.html

Define it like

{{ arg1 := .Get 0 }}
{{ arg2 := .Get 1 }}

<!— do something with $arg1 and $arg2 —>

Then call it like

{{< myshortcode “arg1” “arg2” >}}

wow, super quick reply guys, thank you so much.

These answers all work perfectly, thank you. I got it going!

As like rick, (well sorry, thats making assumpsions :))… I can never remember what I call anything, hence why I wanted to go for positional…plus it’s shorter…

My brain is full of stuff :expressionless:

Thank you!

1 Like

add 2 cents for default values

{{ $value := default "default value" (.Get 1) }}

to use only one parameter if the second has a default value …

1 Like