Reputation: 691
I'm have a pretty silly issue. I'm trying to generate an url in twig using JS variables.
It works when I write them manually:
var url = "{{ path('geolocation', {'latitude':'41.39109','longitude':'2.15485','accuracy':'1114'}) }}";
but it doesn't when I use variables instead:
var url = "{{ path('geolocation', {'latitude':latitude,'longitude':longitude,'accuracy':accuracy}) }}";
What could be happening? Of course the variables exist and are correctly defined.
It seems it doesn't get the parameter correctly:
An exception has been thrown during the rendering of a template ("Parameter "accuracy" for route "geolocation" must match "[^/]++" ("" given) to generate a corresponding URL.").
But when I go:
console.log(latitude + " " + longitude + " " + accuracy);
the result is
41.39109 2.15485 1114
Upvotes: 2
Views: 2042
Reputation: 16033
I am not familiar with TWIG but in regular JS your URL is being assigned a string and Javascript cannot/does not replace variable names within normal strings. You will need to do something like:
var url = "{{ path('geolocation', {'latitude':" + latitude + ",'longitude':" + longitude + ",'accuracy':" + accuracy + "}) }}";
ES6, if you can use it has another way, back tick strings :
var url = `{{ path('geolocation', {'latitude':${latitude},'longitude':${longitude},'accuracy':${accuracy}"}) }}`;
Which mark the expressions to be evaluated by enclosing them in ${...}
Upvotes: -1
Reputation: 39390
I suggest you to use the FOSJsRoutingBundle:
var url = Routing.generate('geolocation', { latitude: latitude, longitude: longitude, accuracy:accuracy })
NB: Take care of add the correct js file inclusion and to expose the route of the controller as described in the doc.
Upvotes: 4