由于包括翻译内容在内的几个原因,我必须构建一个简单的CMS来呈现我的Symfony2应用程序的页面.
我现在的问题是,接缝不可能从字符串中呈现内容.Twig只接受文件.我的内容可能包含像locale或类似的动态部分,因此twig的渲染能力非常有用.
我尝试使用TwibstringBundle渲染它,但它的功能非常有限,并且它不适用于路径功能.
有什么建议可以解决这个问题吗?
Hey*_*ynn 15
请参阅http://twig.sensiolabs.org/doc/functions/template_from_string.html 和http://symfony.com/doc/current/cookbook/templating/twig_extension.html#register-an-extension-as-a-service
{% include template_from_string("Hello {{ name }}") %}
{% include template_from_string(page.template) %}
Run Code Online (Sandbox Code Playgroud)
由于默认情况下未加载字符串加载器,因此需要将其添加到配置中.
# src/Acme/DemoBundle/Resources/config/services.yml
acme.twig.extension.loader:
class: Twig_Extension_StringLoader
tags:
- { name: 'twig.extension' }
Run Code Online (Sandbox Code Playgroud)
Acme/acme是您的应用程序名称,DemoBundle是您要为其启用的软件包.
Symfony 2.7 也让 PHP 变得简单:
$twig = $this->get('twig');
$template = twig_template_from_string($twig, 'Hello, {{ name }}');
$output = $template->render(['name' => 'Bob']));
Run Code Online (Sandbox Code Playgroud)
twig_template_from_string
函数的源码如下:
function twig_template_from_string(Twig_Environment $env, $template)
{
return $env->createTemplate($template);
}
Run Code Online (Sandbox Code Playgroud)
这意味着如果您已经有,twig environment
那么最好直接调用:
$template = $env->createTemplate($templateString);
$parsedContent = $template->render(array('a'=>'b'));
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
7780 次 |
最近记录: |