Ignas Damunskis Ignas Damunskis - 2 months ago 18
Twig Question

Symfony2 - execute TWIG inside JS events

I saw many examples assigning twig to JS variables in

<script>
tag, so I decided to call twig function inside
click
event, but unfortunatelly, clicked or not, it is still executing the
TWIG
code.

$(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

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

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

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

Comments