简体   繁体   中英

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?

youre misunderstanding the purpose of twig. Twig is a templating language .

This means its run on the server before it sends the output to the browser. You would use it to template some JS, before its returned.

If its used correctly (templating is run on a xxx.js.twig file) the twig 'code' is never even present in the file on the client browser at all.

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

<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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM