简体   繁体   English

字符串Twig文件中的Javascript变量

[英]Javascript variable in string twig file

I need to set value of variable id as in following code, 我需要按照以下代码设置变量id的值,

 { type: "control",
                itemTemplate: function(_,item) {

                   var id = item['postId'];
                   var $result = jsGrid.fields.control.prototype.itemTemplate.apply(this, arguments);
                   var $myButton = $("<a style='margin-left:5px;' href='{{ path('updatefull', {'post_id': "+id+"}) }}'><i class='far fa-edit'></i></a>");
                    return $result.add($myButton);
                }
}

But this is not working. 但这是行不通的。 It shows /+id+ instead of the value of id ( which is like /6 for example). 它显示/ + id +而不是id的值(例如,类似于/ 6)。 How to solve this? 如何解决呢?

The Twig template always runs first, on the server, and writes a template which is sent to the client. Twig模板始终总是首先在服务器上运行,并编写一个发送到客户端的模板。 Then JS in that template can run in the browser. 然后,该模板中的JS可以在浏览器中运行。 You're expecting JS to declare the variable id , then Twig to call path , and then JS to continue working, which can't happen. 您期望JS声明变量id ,然后Twig调用path ,然后JS继续工作,这是不可能的。 You'll have to get the id variable into Twig another way. 您必须以另一种方式将id变量添加到Twig中。

Here is how I solved it, 这是我解决的方法,

{ type: "control",
                itemTemplate: function(_,item) {

                   var id = item['postId'];
                   var path = '{{ path("updatefull", {'post_id': 'id'}) }}';
                    path = path.replace("id", id);
                   console.log(path);
                   var $result = jsGrid.fields.control.prototype.itemTemplate.apply(this, arguments);
                   var $myButton = $("<a style='margin-left:5px;' href="+path+"><i class='fa fa-edit'></i></a>");
                    return $result.add($myButton);
                } 

} }

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

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