Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass variable from twig to js

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?

like image 548
nowiko Avatar asked Dec 09 '14 14:12

nowiko


People also ask

How do I transfer data from twig to JavaScript?

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: ...

Can you put JavaScript in twig?

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.

What is twig in JavaScript?

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.


2 Answers

Assign the variable in the template and pick it up with javascript...

<script>
var foo = '{{ foo }}';
alert(foo);
</script>
like image 173
fire Avatar answered Sep 18 '22 21:09

fire


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;
like image 30
qooplmao Avatar answered Sep 18 '22 21:09

qooplmao