doushichun9409
2015-01-11 02:55
浏览 91
已采纳

没有gettext的php twig多语言

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.

图片转代码服务由CSDN问答提供 功能建议

我是php的新手,我使用PHP + JS编写我的第一个网页,没有任何框架(可能稍后)。

我有下一个问题。

如何在没有Gettext或其他插件的情况下在Twig中实现多语言?

类似的东西(在纯PHP中 - 没有问题......但是如何在树枝中使用它)

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

事实上我的项目没有任何限制。 如果Gettext对我来说是最好的解决方案 - 我会用它。 我想我每页只翻译5-10个单词。 为此目的使用Gettext有点奇怪。

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • douguizhuang8276 2015-01-24 13:25
    已采纳

    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

    已采纳该答案
    打赏 评论

相关推荐 更多相似问题