简体   繁体   English

Symfony2 - 在 JS 事件中执行 TWIG

[英]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.我在<script>标签中看到很多将twig赋值给JS变量的例子,所以我决定在click事件中调用twig函数,但不幸的是,无论是否点击,它仍然在执行TWIG代码。

$(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'.最后,当页面加载时,它正在执行树枝,名称为“name”的会话被设置为“value2”。 Twig is rendered way earlier than JS is executed. Twig 在执行 JS 之前呈现方式。 Any ideas how to properly execute twig inside JS?任何想法如何在 JS 中正确执行树枝?

youre misunderstanding the purpose of twig.你误解了树枝的用途。 Twig is a templating language . Twig 是一种模板语言

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.在返回之前,您将使用它来模板化一些 JS。

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.如果使用正确(模板在 xxx.js.twig 文件上运行),则树枝“代码”甚至根本不会出现在客户端浏览器的文件中。

As you stated yourself twig is executed before JS .正如你自己所说的twigJS之前执行。 Twig itself gets compiled into PHP and therefor is interpreted before leaving the server. Twig本身被编译成PHP ,因此在离开服务器之前被解释。

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 :您唯一可以传递给JS本身的是评估方法并将它们存储为变量,也就是说,如果您将它们放在您的twig文件中,例如:

<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执行twig方法并获得正确响应的唯一正确方法是使用 ajax 调用调用控制器

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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