我通常使用这种和平的代码。
<a href="{{ path('person_edit', {'id': 0}) }}' + document.getElementById('person_search').value;">
Goto item
</a>
这将为路由 /edit/{id}
生成正确的 url,但是当我可以将路由更改为 {id}/edit
时,我必须重写此代码。 (不太有效。)
是否有可能在“id”内使用document.getElementById('person_search').value
。
E.G. (不起作用):
<a href="{{ path('person_edit', {'id': 'document.getElementById('person_search').value'}) }}">
Goto item
</a>
提前谢谢您。
最佳答案
不,这是不可能的,因为twig代码在服务器端被解释和执行,例如在浏览器中的javascript执行之前,你可以做的就是使用查询参数,例如:
path = '{{ path('person_edit', {'id': 0}) }}?userId='+document.getElementById("user_id").value;
在 Controller 中你确实喜欢
$request = $this->getRequest();
$userId= $request->get("userId");
但是这样你的 url 将始终带有 id 0,所以忽略它或使用 javascript 构建 url 或使用此包来完成这项工作
关于javascript - 带 id 的 Twig javascript 路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25361844/