The Way to do default value in shortcode

Is this The Way to do “default” value for parameters in shortcode ?

<!-- myshortcode.html -->
{{ myvar := or (.Get "param1") "defaultformyvar" }}
<h1>{{ myvar }}</h1>

<!-- mypost.md -->
{{% myshortcode %}} <!-- <h1>defaultformyvar</h1> -->`
{{% myshortcode param1="othertext" %}} <!-- <h1>othertext</h1> -->

In python I would do

myvar = mydict.get('param1', 'defaultformyvar')

I do this:

<h1>{{ if .Get "param1" }}{{ .Get "param1" }}{{ else }}defaultformyvar{{ end }}</h1>

You can see the embedded shortcodes here for inspiration.

1 Like

Yearh i’ve tried that.
It quickly turns unwieldy if I want to use the param value more than once.

In jinja I would use the default filter like

{{mydata | default("defaultvalue")}}

It would be nice to have a more idiomatic default template func for assigning variables. Let’s say a user can optionally specify a font for a theme. If none is set I could fall back to the default one, assign it to a variable and use it as part of the URL to fetch the font.

I could image a syntax like

{{ $foo := default "Roboto" .Site.Params.font  }}

or

{{ $foo :=  .Site.Params.font | default "Roboto" }}

Especially the last example is very close to the jinja syntax.

default would check if the second value is set. If so the value of .Site.Params.font will be returned. Otherwise Roboto.

/cc @bep this can be done easily. But is it redundant in your eyes?

1 Like
  1. Themes should be able to provide a config.toml with default params. (there is a GH issue)
  2. We have a .Param func already – ad an optional last argument to that (default if none found)

With the two above, everyone should be happy

Edit: It wouldn’t work for shortcodes … But I don’t understand how to implement a general default func. Impress me.

1 Like