2012-05-17 43 views
4

我需要將從路徑生成的未轉義的URL放入input元素。Symfony2樹枝停止轉義路徑

的routing.yml

profile_delete: 
    pattern: /student_usun/{id} 
    defaults: { _controller: YyyXXXBundle:Profile:delete } 

list.html.twig

<input id="deleteUrl" value="{{ path('profile_delete', {id: '$'}) }}"/> 

結果是:

<input id="deleteUrl" value="/student_usun/%24"/> 

我試圖|raw過濾器也把樹枝代碼賭注weil {% autoescape false %}標記和結果仍然相同。

回答

12

Twig沒有帶有url_decode過濾器來匹配它的url_encode one,所以你需要寫它。

SRC

/您/包/嫩枝/分機/ YourExtension.php

<?php 

namespace Your\Bundle\Twig\Extension; 

class YourExtension extends \Twig_Extension 
{ 
    /** 
    * {@inheritdoc} 
    */ 
    public function getFilters() 
    { 
     return array(
      'url_decode' => new \Twig_Filter_Method($this, 'urlDecode') 
     ); 
    } 

    /** 
    * URL Decode a string 
    * 
    * @param string $url 
    * 
    * @return string The decoded URL 
    */ 
    public function urlDecode($url) 
    { 
     return urldecode($url); 
    } 

    /** 
    * Returns the name of the extension. 
    * 
    * @return string The extension name 
    */ 
    public function getName() 
    { 
     return 'your_extension'; 
    } 
} 

然後將其添加到您的服務配置應用程序/配置/ config.yml

services: 
    your.twig.extension: 
     class: Your\Bundle\Twig\Extension\YourExtension 
     tags: 
      - { name: twig.extension } 

然後使用它!

<input id="deleteUrl" value="{{ path('profile_delete', {id: '$'})|url_decode }}"/> 
+1

你應該使用Twig_Filter_Method,不Twig_Function_Method因爲你正在建設一個過濾器。 – umpirsky

+0

已記錄,並更新,謝謝@umpirsky –

+0

我已經命名我的文件「src/HQF/Twig/Extension/UrlDecode.php」。在那個文件中我已經命名了類「UrlDecodeExtension」。在該類中,函數「getName()'」返回「url_decode_extension」。在文件**'app/config/config.yml' **中,而不是'your.twig.extension'我已經使用了'url_decode_twig_extension'。類聲明是'HQF \ Twig \ Extension \ UrlDecodeExtension'。然後,我收到一條錯誤消息:「致命錯誤:Class'HQF \ Twig \ Extension \ UrlDecodeExtension'在2612行中的/[..]/symfony/app/cache/dev/appDevDebugProjectContainer.php中找不到。」請任何想法嗎? –

0

如果你使用:

'url_decode' => new \Twig_Function_Method($this, 'urlDecode') 

,並收到一個錯誤:

Error: addFilter() must implement interface Twig_FilterInterface, instance of Twig_Function_Method given 

取代:

new \Twig_Function_Method($this, 'urlDecode')" 

有:

new \Twig_Filter_Method($this, 'urlDecode')" 

最佳

+0

如果這不起作用,請參閱:http://twig.sensiolabs.org/doc/tags/autoescape.html(我找了大約一個小時,寫了一個過濾器擴展等)我的結論是,樹枝甚至在應用過濾器後也會逃脫輸出,因此您總是例如將得到&而不是&,因此需要自動轉義模板的這一部分。希望有所幫助! – Mike