Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
665 views
in Technique[技术] by (71.8m points)

symfony - Symfony2 Twig stop escaping path

I need to put unescaped URL generated from path into input element.

routing.yml

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

list.html.twig

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

The result is:

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

I tried |raw filter and also put twig code between {% autoescape false %} tag and result is still the same.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Twig doesn't come with a url_decode filter to match its url_encode one, so you'll need to write it.

in src/Your/Bundle/Twig/Extension/YourExtension.php

<?php

namespace YourBundleTwigExtension;

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';
    }
}

And then add it to your services configuration in app/config/config.yml

services:
    your.twig.extension:
        class: YourBundleTwigExtensionYourExtension
        tags:
            -  { name: twig.extension }

And then use it!

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...