php - How to insert javascript var into path on Twig?

152

I want to insert a var declared in javascript into my path to redirect my page.

My code is:

 var id = $(this).attr('data-id');
 windows.location = {{ path("mylink", {id: id}) }};

But I can't know how can insert my var id into path, because when I try this I get error, I'm trying to parse this with +' myvar '+ so concatenating text but I can't.

How can I concatenate or add my var into path?

Thanks!

488

Answer

Solution:

Because PHP is executed on server side, you need to bypass by this way:

 var id = $(this).attr('data-id');
 var path = {{ path("mylink", {id: 0420}) }};

 windows.location = path.replace("0420", id);
252

Answer

Solution:

There is a way to do this without having to use javascriptreplace function. However, it requires some work.

  1. CreateTwig extension to decode URL:

    namespace AppBundle\Twig\Extension;
    
    class UrlDecodeExtension extends \Twig_Extension
    {
        public function getFilters()
        {
            return array(
                new \Twig_SimpleFilter('url_decode', array($this, 'UrlDecodeFilter'))
            );
        }
    
        public function UrlDecodeFilter($url)
        {
            return urldecode($url);
        }
    
        public function getName()
        {
            return 'url_decode_extension';
        }
    }
    
  2. Register your new extension:

    url_decode_extension:
        class: AppBundle\Twig\Extension\UrlDecodeExtension
        tags:
            - { name: twig.extension }
    
  3. Finally, use it in yourTwig template:

    var id = $(this).attr('data-id');
    windows.location = {{ path("mylink", {id: "%s"}) | url_decode | format('"+id+"') | raw }};
    

This is how it is going to render in the browser:

var id = $(this).attr('data-id');
window.location("/your/rendered/url/"+id+"");
867

Answer

Solution:

You should really consider using FOSJsRoutingBundle. It is one of the most commonly used bundles. Its only purpose is to expose the routes you want to client side. Once installed, your code would be :

var id = $(this).attr('data-id');
windows.location = Routing.generate("mylink", {id: id});

People are also looking for solutions to the problem: sql - When to use single quotes, double quotes, and backticks in MySQL

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.