Join the Stack Overflow Community
Stack Overflow is a community of 6.8 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

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

share|improve this question
    
You have a parsing issue in the value of your 'href' attribute. Look at the ' and " you have.. they don't work. – Gerben Jacobs Aug 27 '13 at 8:31
1  
I think you are mixing up things. Your {{ path }} is evaluated by php (via twig) whereas idx is a javascript-variable. This means the value for idx is only available at runtime (client side) and path 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
    
Another workaround would be to create the btn like this: <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
    
Thanks a lot. I have solved the problem by the second methods. That's useful. Thx. @mahok – ojxing Aug 27 '13 at 12:13

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.