[英]How to insert javascript var into path on Twig?
I want to insert a var declared in javascript into my path to redirect my page. 我想在我的路径中插入一个用javascript声明的var来重定向我的页面。
My code is: 我的代码是:
var id = $(this).attr('data-id');
windows.location = {{ path("mylink", {id: id}) }};
But I can't know how can insert my var id into path, because when I try this I get error, I'm trying to parse this with +' myvar '+ so concatenating text but I can't. 但是我不知道如何将var id插入路径,因为当我尝试此操作时遇到错误,我试图用+'myvar'+对此进行解析,因此无法连接文本。
How can I concatenate or add my var into path? 如何连接或将var添加到路径中?
Thanks! 谢谢!
Because PHP is executed on server side, you need to bypass by this way: 由于PHP是在服务器端执行的,因此您需要通过以下方式进行绕过:
var id = $(this).attr('data-id');
var path = {{ path("mylink", {id: 0420}) }};
windows.location = path.replace("0420", id);
There is a way to do this without having to use javascript replace
function. 有一种方法可以执行此操作,而不必使用javascript
replace
功能。 However, it requires some work. 但是,这需要一些工作。
Create Twig
extension to decode URL: 创建
Twig
扩展名以解码URL:
namespace AppBundle\\Twig\\Extension; class UrlDecodeExtension extends \\Twig_Extension { public function getFilters() { return array( new \\Twig_SimpleFilter('url_decode', array($this, 'UrlDecodeFilter')) ); } public function UrlDecodeFilter($url) { return urldecode($url); } public function getName() { return 'url_decode_extension'; } }
Register your new extension: 注册您的新扩展名:
url_decode_extension: class: AppBundle\\Twig\\Extension\\UrlDecodeExtension tags: - { name: twig.extension }
Finally, use it in your Twig
template: 最后,在您的
Twig
模板中使用它:
var id = $(this).attr('data-id'); windows.location = {{ path("mylink", {id: "%s"}) | url_decode | format('"+id+"') | raw }};
This is how it is going to render in the browser: 这是在浏览器中呈现的方式:
var id = $(this).attr('data-id');
window.location("/your/rendered/url/"+id+"");
You should really consider using FOSJsRoutingBundle . 您应该真正考虑使用FOSJsRoutingBundle 。 It is one of the most commonly used bundles.
它是最常用的捆绑软件之一。 Its only purpose is to expose the routes you want to client side.
它的唯一目的是将您想要的路由公开给客户端。 Once installed, your code would be :
安装后,您的代码将是:
var id = $(this).attr('data-id');
windows.location = Routing.generate("mylink", {id: id});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.