2

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

3
  • which framework do you use? Commented Jun 12, 2017 at 10:36
  • 2
    Your variables are defined in the js script (client side), not in the twig (backend side). You have to use $this->render('nameofmy.html.twig', array('latitude' => X, 'longitude' => Y, 'accuracy' => Z); in the controller action. Commented Jun 12, 2017 at 10:42
  • 1
    Shame on me. That's it. Commented Jun 12, 2017 at 10:44

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

-1

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 ${...}

1 Comment

path is a twig function that already will rendered before sending output to the the client. That's why this aproach won't work as the javascript variables are defined client-side and are unknown while rendering the template

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.