简体   繁体   English

使用Silex框架在Twig模板中使用Javascript变量

[英]Using Javascript variable in Twig template using Silex framework

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. 我正在使用Silex框架,我不确定FOS JS是否适用于Silex。 I don't think it does, though. 不过,我不认为这样做。

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. 这样的事情对你有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM