Skip to content

i18n for twig template writers

electrolinux edited this page Mar 14, 2013 · 2 revisions

Adding a simple translatable string

Just wrap your sentence in a call to the __() function:

<h2>{{ __('Latest comments') }}</h2>

This string will be gathered the next time a user hit the "Translations > Messages" menu item, and presented to her for translation in yaml format:

"Latest comments": #

Adding a parametrized string

Use the second argument to pass an hash to the function

<em>{{ __('%name% has commented about %title%',{'%name%':comment.username, '%title%':post.title}) }}</em>

The string will also be provided as a translatable string to the user / translator, and easily translated like this french version:

"%name% has commented about %title%": "%name% a commenté à propos de %title%"

Adding a string about some content-type

In this case, take care of the form to use (singular or plural), and use one of the predefined name for the placeholder, either %contenttype% or %contenttypes%

<a href="#">{{ __('View all %contenttypes% about %search%',
  {'%contenttypes%':contenttype.name,'%search%':search_string}) }}</a>

<a href="#">{{ __('Add a new %contenttype%',
  {'%contenttype%': contenttype.singular_name}) }}</a>

Again, this two sentences will be added to the messages.{locale}.yml for to be translated:

"View all %contenttypes% about %search%": #
"Add a new %contenttype%": #

But a new set of string will also be generated for each user defined content-types,and stored in another translation domain, 'contenttypes':

"View all Pages about %search%": #
"View all Entries about %search%": #
"View all Kitchensinks about %search%": #
"Add a new Page": #
"Add a new Entry": #
"Add a new Kitchensink": #

That way, the end user/perfectionist translator can provide an accurate translation for each content-type.

Adding a large block of text

  1. find a unique key not yet used in translations/en/infos.en.yml, for example mytemplate.info.block1, and add it to the file, along with your text

    mytemplate.info.block1: |
        <p>This is a long string, where you can put as much as you want, even html tags, yes</p>
        <ul><li>itel one</li>
        <li>item two</li>
        <li>...</li>
        </ul>
  2. in your template, use the app.translator.trans() with your newly created key, like this:

    <div>{{ app.translator.trans('mytemplate.info.block1',{},'infos'}) }}<div>

    You need to pass an empty array if you have no parameters, because you need to tell the translator service to look in the 'infos' domain, with is the third parameter.

Clone this wiki locally