-4

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?

Ignas Damunskis
  • 1,515
  • 1
  • 17
  • 44
  • 3
    What you are trying to do is not possible, as you said yourself `twig` is executed before `JS` so you can only pass evaluated functions to `JS` and store them in a variable. If you want to execute some `twig`, you'll need to do this with an ajax call to the controller – DarkBee Sep 26 '16 at 11:32
  • This seem like a solution. Could you post it as answer so I could confirm it as right answer? – Ignas Damunskis Sep 26 '16 at 11:51

2 Answers2

2

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.

Community
  • 1
  • 1
DevDonkey
  • 4,835
  • 2
  • 27
  • 41
1

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

DarkBee
  • 16,592
  • 6
  • 46
  • 58