Symfony2 Twig stop escaping path

前端 未结 2 1947
故里飘歌
故里飘歌 2020-12-06 14:27

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

routing.yml

profile_delete:
  pattern: /student_usun/{id}
  defa         


        
相关标签:
2条回答
  • 2020-12-06 14:43

    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 }}"/>
    
    0 讨论(0)
  • 2020-12-06 15:05

    If you're using:

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

    and receive an error:

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

    replace:

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

    with:

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

    Best

    0 讨论(0)
提交回复
热议问题