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>
-
Be aware. If you are passing user input, that variable should be escaped. Commented Aug 29 at 18:42
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;
-
3This answer is better than the accepted one IMO because you don't need to insert js in twig template. Commented Sep 1, 2020 at 18:33
-
This worked for me. To get data attribute value, I use var id = document.getElementById('video-id').getAttribute('data-id');– SimonCommented Jul 25 at 4:19
-
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. Commented Aug 29 at 18:43
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);
}
-
1Once 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. Commented Jul 19, 2022 at 21:33
You can use this in your twig
<script type="text/javascript">
/* <![CDATA[ */
var settings = {
example: {{ 'something' | trans }}
}
};
/* ]]> */
</script>
then you can access them in your js:
console.log(settings.example);