4

我需要将从路径生成的未转义 URL 放入输入元素中。

路由.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了过滤器,并且还在标签之间放置了树枝代码{% autoescape false %},结果仍然是一样的。

4

2 回答 2

13

Twig 没有附带 url_decode 过滤器来匹配它的url_encode one,所以你需要编写它。

src/Your/Bundle/Twig/Extension/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';
    }
}

然后将其添加到app/config/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 }}"/>
于 2012-05-17T17:08:55.607 回答
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')"

最好的

于 2012-06-07T09:24:41.970 回答