2

I need to generate a dynamic JSON object using some twig function like asset and translate. I'd like to put it in an external settings.js file. I may use include 'settings.js.twig' and put the relevant code in it.

Is this the correct way of generating dynamic javascript in Symfony 2?

2
  • I don't understand exactly what you'd like to do : make a JSON object with javascript? Call a javascript in twig? Commented Jun 22, 2012 at 15:05
  • @GabrielTheron just a json object in a separate file, made up of strings that need to be translated and use some other twig functions. Commented Jun 22, 2012 at 15:20

2 Answers 2

2

This doesn't exactly answer your question, but it's a similar theme. When I need to pass data from the controller/view to the javascript I usually set data attributes on the relevant HTML tags. For example, if I need a route for an AJAX request I will write

<a href="#updateTarget" class="ajaxTrigger" data-ajax-route="{{ path('my_ajax_route') }}">click here for ajax</a>

and then access it with

$('.ajaxTrigger').on('click', function(){
  $.getJSON($(this).data('ajax-route'), function(response) {
    // do something with response
  });
 });
Sign up to request clarification or add additional context in comments.

Comments

0

If you're trying to call a twig in a javascript, you can make a controller that renders the twig that makes your json and call it from a javascript request (ajax or something like that).

Then you have your json in javascript and you can do whatever you need with it.

I think that doesn't completely answer your question though. I'd say you should avoid creating js with twig as much as possible.

1 Comment

That is a solution but it adds another request for the file, while file itself could be rendered without any need of ajax. But thanks anyway.

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.