I want to use the code:
document.getElementById("btn").setAttribute("href", "{{ path('deletecontact', { 'id': "idx" }) }}");
to add attribute to the button to delete the chosed contact.
The idx is the parameter of javascript function. Now the id is always the string "idx", but if I remove the "" to idx, there will be error of symfony.
I have tried to use "+" to linked the string like:
"{{ path('deletecontact', { 'id': "+idx+" }) }}"
But the result is that it will put the string "+idx+" as id.
I have also tried this:
var str1 = "{{ path('deletecontact', { 'id': ";
var str2 = str1 + idx;
var str3 = str2 +" }) }}";
However, there will also error in symfony.
So how can I just put the variable in to the string? Thanks a lot
{{ path }}
is evaluated by php (via twig) whereasidx
is a javascript-variable. This means the value foridx
is only available at runtime (client side) andpath
is rendered prior to that (on the server). You have to specify the url path as a string to javascript, e.g.href: "/path/matching/your/route/" + idx
. Alternatively there is a bundle which makes Symfony-routing accessible to javascript: github.com/FriendsOfSymfony/FOSJsRoutingBundle – dbrumann Aug 27 '13 at 8:44<button id="btn" href="{{ path(..., { 'id': 0 }) }}">...</button>
, i.e. just create the button with a valid path. You can then access the url in your javascript and use it as a kind of template-url replacing the id as needed, e.g. via regexp. – dbrumann Aug 27 '13 at 8:49