ISO country codes to flag emoji

I’m fetching a dataset that contains ISO 3166-1 country codes as string, that I need to convert into flag emojis. This isn’t too difficult in JavaScript, where I can simply do this:

String.fromCodePoint('').map(country_code => 0x1F1A5 + c.charCodeAt()));

Now, I can’t find any seemingly “official” way to do the same in Hugo short-codes, although I came up with something that works:

      {{ range split .addressCountry "" }}
      {{- printf "%c" (delimit . "" | int | add 127397) -}}
      {{ end }}

Now, what makes me skeptical of this approach is that the documentation for “delimit” says:

Loops through any array, slice, or map and returns a string of all the values separated by a delimiter.

There’s no mention of it working for strings, to divide them up into substrings at atom boundaries. However, that seems to work? And looking at the source code, it seems there’s explicit support for strings in there.

Another approach I tried was to use printf the country-code into an emoji-code and passing it through emojify. But it turns out that only a handful of country codes have defined emoji-codes, so that didn’t work.

A final approach would be to have a JSON database mapping country codes to emoji characters. I really want to avoid this, for a few reasons:

  1. The database is just redundant information, this is just a transformation of the data in the first place. Both the country code and the unicode codepoint IS ISO 3166-1, just represented in different ways.
  2. The database will require updates when the ISO 3166-1 spec is changed, which happens due to geopolitical issues.

So I guess my questions are: Is this a reasonable way of doing this? Will this continue to work in the future? If not, what are my alternatives?

1 Like

I see no reason why it shouldn’t work in the future.

If you got it working in Hugo then it’s great. The less JS the better, IMO.

This topic was automatically closed after 4 days. New replies are no longer allowed.