Ignas Damunskis Ignas Damunskis - 1 year ago 223
Twig Question

Symfony2 - execute TWIG inside JS events

I saw many examples assigning twig to JS variables in

tag, so I decided to call twig function inside
event, but unfortunatelly, clicked or not, it is still executing the

$(document).ready(function() {
$('#sign_up_trainee .btn-social').click(function() {
{{ app.session.set('name', 'value1') }}
$('#sign_up_company .btn-social, #sign_up_university .btn-social').click(function() {
{{ app.session.set('name', 'value2') }}

In the end when page is loaded it is executing the twig and session by the name 'name' is set to 'value2'. Twig is rendered way earlier than JS is executed. Any ideas how to properly execute twig inside JS?

Answer Source

As you stated yourself twig is executed before JS. Twig itself gets compiled into PHP and therefor is interpreted before leaving the server.

The only thing you can pass to JS itself are evaluated methods and store them as a variable, that is if you place them inside your twig file e.g. :

    var current_date = '{{ "now" | date('d-m-Y') }}';

The only proper way to execute a twig method and get proper response is by calling the controller with an ajax call

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download