使用 Twig 和 Symfony2 在 javascript 中生成路由
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7626792/
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
Generating routes in javascript with Twig and Symfony2
提问by gremo
Quite odd problem, sorry for asking, i'm quite new to Symfony/Twig. My route requires a mandatory region_id
paramenter:
很奇怪的问题,很抱歉问,我对 Symfony/Twig 很陌生。我的路线需要一个强制性region_id
参数:
ajax_provinces_by_region:
pattern: /ajax/region/{region_id}/provinces
defaults: {_controller: SWAItaliaInCifreBundle:Ajax:provincesByRegion }
requirements: {region_in: \d+}
The questionis: how can i generate this route based on a select
element in javascript (code below)?
该问题是:我怎么能生成基于这个路线select
在JavaScript元素(代码如下所示)?
The problemis: i can't use path
and url
helpers from Symfony as they require to specify the region_id
parameter (this.value
) i can't access because it's a javascript variable (and Twig is compiled server-side).
该问题是:我不能使用path
,并url
因为它们需要指定从symfony辅助region_id
参数(this.value
)无法访问,因为它是一个JavaScript变量(和嫩枝编译服务器端)。
$(document).ready(function() {
$('select#regions').change(function(){
// Make an ajax call to get all region provinces
$.ajax({
url: // Generate the route using Twig helper
});
});
});
回答by Ben
I know it's an old question, but just in case you don't want to install a bundle like FOSJsRoutingBundle, here's a little hack:
我知道这是一个老问题,但以防万一你不想安装像 FOSJsRoutingBundle 这样的包,这里有一个小技巧:
var url = '{{ path("yourroute", {'region_id': 'region_id'}) }}';
url = url.replace("region_id", this.value);
'region_id' is just used as a placeholder, then you replace it in JS with your actual variable this.value
'region_id' 只是用作占位符,然后你在 JS 中用你的实际变量 this.value 替换它
回答by igorw
You can use the FOSJsRoutingBundle.
您可以使用FOSJsRoutingBundle。
回答by George
url: "{{ path('SampleBundle_route',{'parameter':controller_value}) }}"
Where SampleBundle_route
is a valid path defined in routing.yml or annotatins.
SampleBundle_route
在routing.yml 或annotatins 中定义的有效路径在哪里。
For testing, write this in the twig template:
为了测试,在树枝模板中写下这个:
<script>
var url= "{{ path('SampleBundle_route') }}";
alert(url);
</script>
回答by Imen AchOurii
* @Route("/{id}/edit", name="event_edit", options={"expose"=true})
回答by Yoann Kergall
You can use data attribute in your HTML:
您可以在 HTML 中使用 data 属性:
<select id="regions">
{% for region in regions %}
<option data-path="{{ path('ajax_provinces_by_region', {'region_id': region.id}) }}">...</option>
{% endfor %}
</select>
then in your javascript:
然后在你的javascript中:
$('select#regions').on('change', function() {
let path = $(this).find(':selected').data('path')
$.ajax({
'url': path
})
})