Reputation: 6353
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!
Upvotes: 0
Views: 934
Reputation: 330
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});
Upvotes: 0
Reputation: 4304
There is a way to do this without having to use javascript replace
function. However, it requires some work.
Create Twig
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';
}
}
Register your new extension:
url_decode_extension:
class: AppBundle\Twig\Extension\UrlDecodeExtension
tags:
- { name: twig.extension }
Finally, use it in your Twig
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+"");
Upvotes: 0
Reputation: 399
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);
Upvotes: 1