简体   繁体   English

在.twig文件苗条框架中使用php代码

[英]Using php code in .twig file slim framework

I am using Slim Framework for the first time and also using twig for templatizing. 我是第一次使用Slim Framework,也使用树枝进行模板化。 I have a land.twig file the contents of that file are 我有一个land.twig文件,该文件的内容是

 <form action="index.html" method="get">
          <div class="form-group">
            <input type="text" class="form-control" placeholder="Full Name">
          </div>
</form>

I also have a string file to support multi-language and the way I call the string for translation is lang("some_string"); 我也有一个字符串文件来支持多语言,而我称该字符串进行翻译的方式是lang(“ some_string”); . The land.twig file is rendered by a controller. land.twig文件由控制器渲染。 My question is how can I add lang("some_string") within placeholder attribute for html elements in that twig file ? 我的问题是如何在那个树枝文件中的html元素的占位符属性内添加lang(“ some_string”)?

You could use Twig_SimpleFilter. 您可以使用Twig_SimpleFilter。

require_once '/path/to/lib/Twig/Autoloader.php';
Twig_Autoloader::register();

$loader = new Twig_Loader_Filesystem('/path/to/templates');
// an anonymous function
$filter = new Twig_SimpleFilter('lang', function ($string) {
    //do stuff
    return $string;
});

$twig = new Twig_Environment($loader);
$twig->addFilter($filter);

Then in your template you can use 然后,您可以在模板中使用

 <input type="text" class="form-control" placeholder="{{ 'Full Name'|lang }}">

Since you are using slim and its twig integration you have to add the filter within the twig component. 由于您使用的是苗条及其细枝集成,因此您必须在细枝组件中添加过滤器。

// Register component on container
$container['view'] = function ($container) {
   $view = new \Slim\Views\Twig('path/to/templates', [
       'cache' => 'path/to/cache'
    ]);
    $view->addExtension(new \Slim\Views\TwigExtension(
        $container['router'],
        $container['request']->getUri()
    ));

    $filter = new Twig_SimpleFilter('lang', function ($string) {
        //do stuff
        return $string;
    });

    $view->getEnvironment()->addFilter($filter);

    return $view;
};

Other than that twig has a i18n extension . 除此以外,该树枝还具有i18n扩展名

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM