简体   繁体   English

使用Twig和Symfony2在javascript中生成路由

[英]Generating routes in javascript with Twig and Symfony2

Quite odd problem, sorry for asking, i'm quite new to Symfony/Twig. 很奇怪的问题,抱歉,我对Symfony / Twig很新。 My route requires a mandatory region_id paramenter: 我的路线需要强制的region_id参数:

ajax_provinces_by_region:
  pattern: /ajax/region/{region_id}/provinces
  defaults: {_controller: SWAItaliaInCifreBundle:Ajax:provincesByRegion }
  requirements: {region_in: \d+}

The question is: how can i generate this route based on a select element in javascript (code below)? 问题是:我如何根据javascript(下面的代码)中的select元素生成此路由?

The problem is: 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). 问题是:我不能使用来自Symfony的pathurl助手,因为他们需要指定我无法访问的region_id参数( this.value ),因为它是一个javascript变量(并且Twig是服务器端编译的)。

$(document).ready(function() {
    $('select#regions').change(function(){

        // Make an ajax call to get all region provinces
        $.ajax({
            url: // Generate the route using Twig helper
        });

    });
});

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替换它

您可以使用FOSJsRoutingBundle

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: 要进行测试,请在twig模板中写下:

<script>
    var url= "{{ path('SampleBundle_route') }}";
    alert(url);
</script>
 * @Route("/{id}/edit", name="event_edit", options={"expose"=true})

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
    })
})

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

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