Language flags

How to add language flags to Jekyll?

Posted by wojtek on September 16, 2018 in Development

As I’m writing my blog in two languages I thought it would be nice to show which posts are written in which language. Not that you can’t figure this out from a title itself. But why not to be absolutely clear on what you can expect from each post. And that’s a good opportunity to do something in Jekyll and write a blog post about it.

Get some flags

First, you need to get some flags… not the actual flags but images of them. Personally, I’ve used Flag Sprites and generated two flags for two languages I’m supporting. Download them and unpack somewhere into your website folder. There is a nice readme file which explains how you can add flags to your website. We will start by adding CSS stylesheet to page template, simply paste below code to <head> section:

<link href="/assets/flags/flags.min.css" rel=stylesheet type="text/css">

Of course change /assets/flags/ to relative location in your structure.

Configure your blog

Now we have to add some configuration to _config.yml to make thing a little bit more flexible.

        flag: pl
        name: Polski
        flag: gb
        name: English

Basically now you can setup human-readable name for a language and transform language into the country code for a flag. As you’ve probably noticed for English I’m using Union Jack so my language code is en but flag code is gb.

Add flags

It’s the time to add those flags somewhere, in my case I’ve added them to standard post list as well as my yearly post list.

{% if post.language %}
    <img src="/assets/flags/blank.gif"
         class="flag flag-{{ site.languages[post.language].flag }}"
         alt="{{ site.languages[post.language].name }}" />
{% endif %}

So if post.language is set then display a picture with specific class which is set to flag-{{site.languages[post.language].flag}} that’s the key element we are using configuration for this language.

Set your language

Finally, it’s the time to set the language of posts. You need to add language configuration to Front Matter of posts that you want to display a flag.

language: en

I hope that this simple tutorial not only showed you how to add flags but inspired how in many different ways you can extend your Jekky based website. If you have any interesting ideas please share them in comments.