Search code examples
internationalizationtwigslimgettexttwig-extension

How do I create a plural translation using Twig and the i18n extension?


I'm using the Slim PHP framework with Twig and the Twig extension i18n. I need to create a plural translation that displays the number of messages in an array. I'm using a text editor to create the .po file and Poedit to compile it to a .mo file.

Here's my template:

        {% set count=messages|length %}
        {% trans %}
            Showing the last message.
        {% plural count %}
            Showing the last {{count}} messages.
        {% endtrans %}<br>

And here's my .po file (for Swedish translation):

msgid "Showing the last message."
msgid_plural "Showing the last %count messages."
msgstr[0] "Visar det senaste meddelandet."
msgstr[1] "Visar de %count senaste meddelandena."

This doesn't work, it gives me

Visar de %count senaste meddelandena.

even when count is 16.

Where am I going wrong?


Solution

  • That %count should instead be %count%. The documentation of the i18n extension has this example:

    {% trans %}
        Hello {{ name }}!
    {% endtrans %}
    

    During the gettext lookup these placeholders are converted. {{ name }} becomes %name% so the gettext msgid for this string would be Hello %name%!.