如何用树枝渲染字符串/数据库中的内容? [英] How to render content from string/database with twig?
问题描述
由于包括内容翻译在内的几个原因,我不得不构建一个简单的 CMS 来呈现我的 Symfony2 应用程序的页面.
Because of several reasons including translation of content I had to build a simple CMS to render the pages of my Symfony2 application.
我的问题是似乎不可能从字符串呈现内容.Twig 只接受文件.我的内容可能包含像语言环境或类似的动态部分,所以树枝的渲染能力会非常有用.
My problem is that is seems impossible to render content from a string. Twig only accepts files. My content may contain dynamic parts like locale or similar, so the render power of twig would be very useful.
我尝试使用 TwibstringBundle 来渲染它,但它的功能非常有限,并且没有使用路径函数.
I tried to render it using the TwibstringBundle, but its functionality is quite limited and it does not work with the path-function.
推荐答案
参见 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) %}
由于默认情况下不加载字符串加载器,因此您需要将其添加到您的配置中.
Since the string loader is not loaded by default, you need to add it to your config.
# src/Acme/DemoBundle/Resources/config/services.yml
acme.twig.extension.loader:
class: Twig_Extension_StringLoader
tags:
- { name: 'twig.extension' }
其中 Acme/acme 是您的应用程序名称,DemoBundle 是您要为其启用它的包.
Where Acme/acme is your application name and DemoBundle is the bundle you want to enable it for.
这篇关于如何用树枝渲染字符串/数据库中的内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!