Search code examples
javascripttwigjsgrid

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?


Solution

  • 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.