A plugin I maintain uses Twig templates to produce HTML (and some other outputs). I've tried using __() within these (first adding the i18n functions with $twig->addFunction()) but it doesn't work. The strings are output correctly, but not picked up for inclusion in the .pot file.

For example the following in base.twig should be translatable:

{{__('Search', 'tabulate')}}

I'm obviously off on the wrong track here. Anyone got any pointers for doing this?

  • 1
    Try processing your translations in PHP and transferring them into TWIG as variables? I am not familiar with the language, but it seems that a PHP array could work. – Nathan Powell Jan 22 '16 at 5:59
  • Yeah I've been wondering about that... I'm thinking it might be the only way. I'm seeing if gettext can be made to look elsewhere... – Sam Wilson Jan 22 '16 at 6:06
  • Seeing if gettext can do something different sounds backwards, I would trash TWIG before going there. It's PHP! – Nathan Powell Jan 22 '16 at 6:15
  • A google search got me to this page. I really don't see this topic relative to WordPress tho. – Nathan Powell Jan 22 '16 at 8:25

Here's how the Timber plugin handles this:

$twig->addFunction( '__', new Twig_SimpleFunction( '__', function ( $text, $domain = 'default' ) {
    return __( $text, $domain );
} ) );

I'm guessing you're doing something similar, in which case the reason these are being skipped is that you're using a variable for the text domain. Have you tried hard-coding the text domain?

$twig->addFunction( '__', new Twig_SimpleFunction( '__', function ( $text ) {
    return __( $text, 'your-text-domain' );
} ) );

If that's not an option or it doesn't work you'll need to handle all of the translation in PHP and pass the translated text to your Twig templates as suggested by another commenter.

  • No, I've tried it with hard-coded text domain (see my example above) but the problem seems to be that the __() isn't discoverable in Twig files and so not offered for translation with the normal tools. Strings can be added manually though. But I suspect I'm going to have to have a separate string-to-words file... :) – Sam Wilson Feb 28 '16 at 5:25

I had the same problem. Twig files are not automatically recognized when you use Poedit to work on your translations. The section about Generating .po files using Poedit in the Timber Wiki might help you set it up to make it work.

The Twig Gettext Extractor that is mentioned there didn’t work well for me. Definitely try the parser for Python, which is also described as an alternative in the link above.

Your Answer


By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.