Table of Contents

Printing Unicode Characters in Hugo

My learning experience with printf in Golang and Hugo.

4 Oct 2023. 197 words.


Hugo uses Golang’s fmt.Sprintf to format strings.

{{ $var := "world" }}
{{ printf "Hello %s." $var }} {{/* Hello world. */}}

While we mostly need standard options such as %s (print as string), %d (integer), $f (float), and so on, there are some other options that are useful in Hugo.

For example, the following code prints the value in a Go-syntax:

{{ $var := dict "this" 1 "that" 2 }}
{{ printf "%#v" $var }} {{/* map[string]interface {}{"that":2, "this":1} */}}

Dynamic character using %c

The %c option prints a character corresponding to the given Unicode code point. Using this option, we can create a simple shortcode that converts hex to character.

layouts/shortcodes/unicode.html
{{ .Get 0 | int | printf "%c" }}

Using this shortcode, we can print a character using its Unicode code point:

{{< unicode 0x1F4A9 >}} {{/* 💩 */}}

Here is another example. Say we want to print a circled number. We know that U+2460 corresponds to ①, and U+2461 corresponds to ②, and so on, so we construct the following logic:

{{ $num := 4 }}
{{ $code := add 0x245F $num }} {{/* U+2463 */}}
{{ printf "%c" $code }}        {{/* ④ */}}