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?
Using a data attribute to pass a single field If you have a small amount of data to share with JavaScript then use a named data attribute. First add the named data attribute to an element. ❗ If the value has a chance of containing a " or < then add an escape filter: ...
Your Twig component doesn't need to rely only on inline code - if you want to include external JS file from within Twig, you can use registerJsFile function. Link to this file will also be included at the end of the template. There is also CSS equivalent of js - css tag.
Twig.js is a pure JavaScript implementation of the Twig PHP templating language (https://twig.symfony.com/) The goal is to provide a library that is compatible with both browsers and server side JavaScript environments such as node. js.
Assign the variable in the template and pick it up with javascript...
<script>
var foo = '{{ foo }}';
alert(foo);
</script>
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With