javascriptsymfonytwig

How to generate path with JavaScript variable?


I normally use this piece of code.

<a href="{{ path('person_edit', {'id': 0}) }}' + document.getElementById('person_search').value;">
   Goto item 
</a>

Which will generate correct url for route /edit/{id}, but when I can change routes into {id}/edit I have to rewrite this code.(Not so effective.)

Is it some possibility to use document.getElementById('person_search').value inside an 'id'.

E.G. (doesn't work):

<a href="{{ path('person_edit', {'id': 'document.getElementById('person_search').value'}) }}">
   Goto item 
</a>

Thank you in advance.


Solution

  • No this is not possible as the twig code gets interpreted and executed serverside e.g way before your javascript in your browser executes, what u can definetly do is use query parameters like :

    path = '{{ path('person_edit', {'id': 0}) }}?userId='+document.getElementById("user_id").value;
    

    in controller you do like

    $request = $this->getRequest();
    $userId= $request->get("userId");
    

    But this way your url will always be with id 0 so ommit it or build the url with javascript or use this bundles that does the job

    Fos Routing Js Bundle