2012-03-21 69 views
4

由於包括內容翻譯在內的多種原因,我必須構建一個簡單的CMS來呈現我的Symfony2應用程序的頁面。從字符串/數據庫渲染內容並生成鏈接

我現在的問題是,接縫不可能呈現來自字符串的內容。小枝只接受文件。我的內容可能包含動態部分,如語言環境或類似內容,因此枝條的渲染能力將非常有用。

我試圖使用TwibstringBundle來渲染它,但它的功能非常有限,並且它不適用於路徑功能。

任何建議來解決這個問題?

+0

它們是如何存儲在數據庫中的? – max 2012-03-22 00:46:21

+0

它們存儲爲帶有一些html標記的簡單文本。 – madc 2012-03-22 12:20:57

回答

15

看到http://twig.sensiolabs.org/doc/functions/template_from_string.htmlhttp://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) %} 

由於串加載器默認不加載,你需要將它添加到你的配置。

# src/Acme/DemoBundle/Resources/config/services.yml 
acme.twig.extension.loader: 
    class:  Twig_Extension_StringLoader 
    tags: 
     - { name: 'twig.extension' } 

其中Acme/acme是您的應用程序名稱,DemoBundle是您希望爲其啓用的包。

+0

看起來很有希望,謝謝你的回答。我將在稍後檢查並報告。 – madc 2012-10-15 14:01:30

+0

昨晚執行它。我發現迄今爲止唯一的缺點是,你調用的任何樹枝擴展也使用字符串加載器。例外等不能很好地處理。字符串加載器不建議在外部使用,因爲結果可能不如您期望的那樣(即擴展,包括等等)。 – Heyflynn 2012-10-15 17:32:59

+5

添加了新的支持樹枝的方式來將字符串加載爲模板 – Heyflynn 2012-11-29 18:01:09

3

Symfony的2.7使得從PHP這個簡單,太:

$twig = $this->get('twig'); 
    $template = twig_template_from_string($twig, 'Hello, {{ name }}'); 
    $output = $template->render(['name' => 'Bob'])); 
+0

爲什麼只有Symfony 2.7?也適用於Symfony 2.3。 – 2015-07-13 09:49:27

+1

不適用於我。 '我試圖從命名空間'AppBundle \ Controller'' '嘗試從名稱空間調用函數「twig_template_from_string」。但是,這對我有用:'$ this-> get('twig') - > createTemplate('Hello,{{name}} ');' – Atan 2016-03-17 11:12:06

+0

爲什麼奇怪的全局函數?對於一個像樹枝一樣的項目來說,很不錯 – mblaettermann 2016-04-21 11:18:29

2

twig_template_from_string功能的源代碼如下:

function twig_template_from_string(Twig_Environment $env, $template) 
{ 
    return $env->createTemplate($template); 
} 

這意味着,如果你已經有了一個twig environment那麼最好打電話直接:

$template = $env->createTemplate($templateString); 
$parsedContent = $template->render(array('a'=>'b'));