简体   繁体   中英

Javascript variable in string twig file

I need to set value of variable id as in following code,

 { 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). How to solve this?

The Twig template always runs first, on the server, and writes a template which is sent to the client. Then JS in that template can run in the browser. You're expecting JS to declare the variable id , then Twig to call path , and then JS to continue working, which can't happen. You'll have to get the id variable into Twig another way.

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);
                } 

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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