Is there some way to pass variables from twig to javascript file that lay in public/js directory of bundle. Or do I need to assign my variables in template and then include my script file where vars will be used?
4 Answers
Assign the variable in the template and pick it up with javascript...
<script>
var foo = '{{ foo }}';
alert(foo);
</script>
1 Comment
Maciej Paprocki
Be aware. If you are passing user input, that variable should be escaped.
Another way without having to have your javascript file as a template would be to have the javascript value as a data-* attribute and then get that from your javascript file. This would mean that your javascript wouldn't necessarily be coupled to your twig file.
<a href="#" data-id="{{ entity.id }}" id="some-link">Link</a>
With jQuery..
var id = $('#some-link').data('id');
With regular javascript (i think)..
var id = document.querySelector('#some-link').dataset.id;
3 Comments
Sébastien Gicquel
This answer is better than the accepted one IMO because you don't need to insert js in twig template.
Simon
This worked for me. To get data attribute value, I use var id = document.getElementById('video-id').getAttribute('data-id');
Maciej Paprocki
Be aware that if you pass something else than a numeric id you might end up having problems. Specially, user input. Using |e('html_attr') should be the correct way.
watch this
variable in twig: fpoint = [{'id': 1},{'id': 2}]
if it is an array
var fg = $.parseJSON('{{ fpoint | json_encode | raw }}');
for(k in fg){
console.log("fpoint: ", fg[k].id);
}
1 Comment
Félix Adriyel Gagnon-Grenier
Once the initial knee-jerk reaction of "gods this is horrible" is passed, serializing to JSON and back is probably the least bad way of passing actual data structures instead of just strings in parsed javascript templates.