Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2 Twig stop escaping path

Tags:

twig

symfony

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.

like image 672
koral Avatar asked Dec 12 '22 02:12

koral


1 Answers

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

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

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

And then use it!

<input id="deleteUrl" value="{{ path('profile_delete', {id: '$'})|url_decode }}"/>
like image 63
Peter Bailey Avatar answered Dec 17 '22 06:12

Peter Bailey