Search code examples
phptwigtranslationmultilingual

php twig multilanguage without gettext


I am novice in php and I write my first web page using PHP + JS without any frameworks (maybe later).

I have the next question.

How to implement multi language in Twig without Gettext or other plugins?

Something like that (in pure PHP - no questions... but how use it in twig)

$lang=array(
"about_site" => "о нас",
"project" => "проект",
"team" => "команда");

In fact my project has no restrictions. If Gettext is the best solution for me - I'll use it. I thought I'll have to translate only 5-10 words per page. Using Gettext for this purpose is a bit strange.


Solution

  • You can easily use a php array like yours for translation in twig. Just pass the array to the twig template:

    /* $twig is a is an instance of Twig_Environment */
    $template = $twig->loadTemplate('yourtemplate.html');
    
    $templateVars['trans'] = array(
      "about_site" => "о нас",
      "project" => "проект",
      "team" => "команда"
    );
    echo $template->render($templateVars);
    

    And in the template:

    <!-- a lot of html stuff -->
    <ul>
      <li><a href="#">{{ trans.about_site }}</a></li>
      <li><a href="#">{{ trans.project }}</a></li>
      <li><a href="#">{{ trans.team }}</a></li>
    </ul>
    

    But mind, if you have complex translations with singular/plural expressions, variables, date expressions etc. I would strongly recommend you to use the twig i18n extension that is built upon gettext: http://twig.sensiolabs.org/doc/extensions/i18n.html