Javascript 字符串 twig 文件中的变量
Javascript variable in string twig file
我需要按照以下代码设置变量 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);
}
}
但这不起作用。它显示 /+id+ 而不是 id 的值(例如 /6)。如何解决?
Twig 模板总是先 运行 在服务器上,然后编写发送到客户端的模板。然后该模板中的JS可以在浏览器中运行。你期望 JS 声明变量 id
,然后 Twig 调用 path
,然后 JS 继续工作,这是不可能发生的。您必须以另一种方式将 id
变量放入 Twig。
我是这样解决的,
{ 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);
}
}
我需要按照以下代码设置变量 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);
}
}
但这不起作用。它显示 /+id+ 而不是 id 的值(例如 /6)。如何解决?
Twig 模板总是先 运行 在服务器上,然后编写发送到客户端的模板。然后该模板中的JS可以在浏览器中运行。你期望 JS 声明变量 id
,然后 Twig 调用 path
,然后 JS 继续工作,这是不可能发生的。您必须以另一种方式将 id
变量放入 Twig。
我是这样解决的,
{ 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);
}
}