2015-04-12 27 views
2

我有這個模板吧:如何避免替換文字?

<blockquote> 
    <p>{{ message|replace({"\r\n\r\n":'</p><p>', "\r\r":'</p><p>', "\n\n":'</p><p>'}) }}</p> 
</blockquote> 

有了這個輸入

WOOP德鬥\ r \ NLA-DEE-DA \ r \ n \ r \ nFoo範德Bar \ r \ n \ r \ nMojo < script> alert('Test'); </SCRIPT>

它呈現這樣的:

Woop-de-doo La-dee-da</p><p>Foo van der Bar</p><p>Mojo<script>alert('Test');</script> 

嗯,這是一個恥辱,我希望我的替代HTML渲染。如果您在結束巴掌|raw,它的工作原理:

Woop-de-doo La-dee-da 

Foo van der Bar 

Mojo 

除非它也運行從輸入文字,這顯然我希望有發生的(潛在的危險)的腳本。

如何告訴Twig字面上使用我的替換文本,但仍然保持輸入文本轉義?

回答

2

你有沒有嘗試使用php方法nl2br? http://php.net/manual/en/function.nl2br.php

,你可以使用它作爲一個樹枝過濾

http://twig.sensiolabs.org/doc/filters/nl2br.html

{{ "I like Twig.\nYou will like it too."|nl2br }} 
如果你想專門有你所描述的轉變,你想要它做一個預逃生,然後呈現在

html你將不得不編寫你自己的過濾器

對於這個讓我們來看看如何實現nl2br

https://github.com/twigphp/Twig/blob/11f9ebe8b6fb4d18d02591c4a042d1cab94b72eb/lib/Twig/Extension/Core.php#L172

new Twig_SimpleFilter(
    'nl2br', 
    'nl2br', 
    array('pre_escape' => 'html', 'is_safe' => array('html')) 
) 

所以現在爲了寫自己的擴展,你可以按照本

http://symfony.com/doc/current/cookbook/templating/twig_extension.html

class AppExtension extends \Twig_Extension 
{ 
    public function getFilters() 
    { 
     return array(
      new \Twig_SimpleFilter(
       'doubleline2paragraph', 
       array($this, 'doubleLine2Paragraph'), 
       array('pre_escape' => 'html', 'is_safe' => array('html')) 
      ), 
     ); 
    } 

    public function doubleLine2Paragraph($text) 
    { 
     // your transformation 

     return $text; 
    } 

    public function getName() 
    { 
     return 'app_extension'; 
    } 
} 

然後對其進行註冊(如上面的鏈接解釋),這樣你可以使用它

{{ "your text" | doubleline2paragraph }} 
+0

它不會做我想要的。正如我的代碼演示的那樣,我想要雙換行符來關閉並打開新段落,'

'。 – Alex

+0

@Alex我編輯了我的答案 –

+0

謝謝。我希望避免寫我自己的,但除非有人出面證明你錯了,我會接受這個答案。 – Alex