简体   繁体   English

Symfony 4 - 有没有办法使用脚本函数来设置树枝变量?

[英]Symfony 4 - Is there a way to use a script function to set a twig variable?

I would like to set a prompt box fromjavascript and pass the text entered to my twig attribute msg.我想从javascript设置一个提示框并将输入的文本传递给我的树枝属性msg。

But I don't know how I can pass from my script to my twig.但我不知道如何从我的脚本传递到我的树枝。

There is my code for now.现在有我的代码。

<script type="text/javascript">
    function PromptMessage() {
        var saisie = prompt("Saisissez votre texte :", "Texte par défaut");
        console.log(saisie);

    }
</script>

{# It works with an hardcode value in twig #}
{% set msg = 'egaezrf' %}

    <button type="button" class="btn btn-success" onclick="window.location.href = '{{ path('email_index', {'iduser': onlineorder.iduser.iduser, 'msg': msg}) }}';">Send Email</button>

There seems to be a fundamental misunderstanding here.这里似乎存在一个根本性的误解。 Twig code runs on the server, before the JS gets anywhere near being executed.在 JS 接近执行之前,Twig 代码在服务器上运行。 Once the Twig code has been executed, then the resulting page goes to the browser and the JS is executed.一旦树枝代码已被执行,然后在结果页转到浏览器并执行JS。

In effect, this question is "how can my code travel back in time"?实际上,这个问题是“我的代码如何回到过去”?

I recommend using the Javascript Routing system ( https://symfony.com/doc/current/routing/generate_url_javascript.html ) to generate the url you need in Javascript directly.我建议使用 Javascript 路由系统 ( https://symfony.com/doc/current/routing/generate_url_javascript.html ) 直接在 Javascript 中生成您需要的 url。 This looks something like这看起来像

// JAVASCRIPT
    var url = Routing.generate('email_index', {
        'iduser': iduser,
        'msg': saisie
    });

Okay, you've asked a follow-up question about how this should all be put together.好的,你已经问了一个关于如何将所有这些组合在一起的后续问题。 I'd recommend not using the onclick attribute of the button element: it may be what you've done in class but it's considered outdated.我建议不要使用 button 元素的onclick属性:它可能是你在课堂上所做的,但它被认为已经过时了。 Get a reference to your button:获取对按钮的引用:

var myButton = document.querySelector("button");

Pass the iduser value into Javascript (one of the two options):iduser值传递给 Javascript(两个选项之一):

var iduser = {{ onlineorder.iduser.iduser }}; // if it's an int
var iduser = "{{ onlineorder.iduser.iduser | e('js') }}"; // if it's a string. 
// the e('js') is a Twig function to safely generate Javascript strings, see
// https://twig.symfony.com/doc/2.x/filters/escape.html

Then use the first code block above to generate url .然后使用上面的第一个代码块生成url

Finally set the event handler on the button: (docs)最后在按钮上设置事件处理程序:( 文档)

button.addEventListener("click", function(event) {
    window.location.href = url;
});

If you have any further issues I'd recommend asking your lecturer/supervisor.如果您有任何其他问题,我建议您询问您的讲师/主管。

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

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