Concatinating Strings in Hugo

A Quick tip around string concatination.

What doesnt works

{{ $a := $b + $c }}

or

{{ $a := $b $c }}

or

{{ $a := $b . $c }}

However what does work is

$a := printf "%s" $a | printf "%s"

However if you try to pipe multiple of these in one string like

$a := printf "%s" $a | printf "%s" $b | printf "%s"

This would add extra charcters

%!(EXTRA string=WORLD)

took me a while to figure out my own daftness

printf "%s" $a | printf "%s" $b | printf "%s" This is akin to passing output from one command to another, the second command takes input from first commands output.

so a slightly tweaked version

printf "%s" $a | printf "%s%s" $b | printf "%s"

See that extra %s on second set. thats for the output coming from the first command.

Anyone trying to piece this together would realize the string has to be concatenated in inverted order.

so if I want $a + $b + $c i will have to do it this way.

printf "%s" $c | printf "%s%s" $b | printf "%s%s" $a | printf "%s"

Remember we dont need to increase %s as we move to left. You ask why, coz the previous command output has gotten squasted into a single string.
Thats it for today.

Note: The article was first published on now defunct : https://til.anantshri.info/post/hugo_string_concat/

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top