Shortcodes in Hugo are basically chunks of HTML code that can be used in our content files. You can use built-in shortcodes like youtube or create your own.
Create custom shortcode
Here are the basic steps to create your own custom shortcode:
- Create a file
layouts/shortcodes/shortcode_name.html
- Add your HTML code to the
shortcode_name.html
file - Call your shortcode with
{{< shortcode_name >}}
Shortcode example
Let's create a simple Hugo shortcode that displays the temperature:
- Create a file
layouts/shortcodes/temp.html
- Add this code to
temp.html
:<span>{{ .Get 0 }}°C</span>
- Use it like this:
which will display:It is {{< temp 24 >}} outside
It is 24°C outside
In this example, we accessed the parameter by position using {{ .Get 0 }}
, where the value is 24. We can also access parameters by name.
Using named parameters
To use named parameters, modify the shortcode HTML code like this:
<span>{{ .Get "c" }}°C</span>
You can then use it like this:
It is {{< temp c=24 >}} outside
Accepting both named and positional parameters
To accept both named and positional parameters, we can use like this:
{{- $c := .Get "c" | default (.Get 0) -}}
<span>{{ $c }}°C</span>
This will allow these two usages to be valid and produce the same result:
{{< temp 24 >}}
{{< temp c=24 >}}
Using multiple parameters
Here's an example of using multiple parameters:
{{- $c := .Get "C" | default (.Get 0) -}}
{{- $as := strings.ToUpper (.Get "as" | default (.Get 1)) -}}
{{ $val := cond (eq ($as) "F") (add 32 (mul $c 1.8)) $c }}
{{ $type := cond (eq ($as) "F") "°F" "°C" }}
<span>{{ $val }}{{ $type }}</span>
Here are some examples of how to use this shortcode and the expected results:
{{< temp 24 >}}
→ 24°C{{< temp C=24 >}}
→ 24°C{{< temp 24 F >}}
→ 75.2°F{{< temp C=24 as=F >}}
→ 75.2°F
Here's a breakdown of what's happening in the shortcode:
- $c = (value of the parameter “C”) or (the first parameter):
{{- $c := .Get "C" | default (.Get 0) -}}
- $as = (the value of the parameter “as”) or (the second parameter):
{{- $as := strings.ToUpper (.Get "as" | default (.Get 1)) -}}
- $val = (convert to Fahrenheit if $as is F) otherwise (use $c as Celsius value):
{{ $val := cond (eq ($as) "F") (add 32 (mul $c 1.8)) $c }}
- $type = if is Fahrenheit use "°F", if is Celsius use "°C":
{{ $type := cond (eq ($as) "F") "°F" "°C" }}