使用 Silex 框架在 Twig 模板中使用 Javascript 变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12009271/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using Javascript variable in Twig template using Silex framework
提问by Moismyname
I am trying to create a route inside of some Javascript inside of a Twig template and need to use a JS variable as a value to a route parameter.
我正在尝试在 Twig 模板内的某些 Javascript 内创建路由,并且需要使用 JS 变量作为路由参数的值。
Example:
例子:
window.location.href = {{ path('post_display', { 'id': this_is_where_i_need_to_use_the_js_var }) }};
I am using the Silex framework and am unsure if FOS JS works for Silex. I don't think it does, though.
我正在使用 Silex 框架,但不确定 FOS JS 是否适用于 Silex。不过,我认为不会。
回答by Maerlyn
Twig, since it's written in PHP
, runs on the server, completely separately than the javascript code, so what you want needs a workaround.
Twig,因为它是用 编写的PHP
,在服务器上运行,与 javascript 代码完全分开,所以你想要的需要一个解决方法。
First, generate the route, but with a placeholder, then replace that with the value of your variable when neccessary:
首先,生成路线,但使用占位符,然后在必要时将其替换为变量的值:
var route = "{{ path('post_display', { 'id': "PLACEHOLDER" }) }}";
window.location = route.replace("PLACEHOLDER", js_variable);
Something like this should work for you.
像这样的事情应该适合你。