gpt4 book ai didi

php - Symfony、fos_js_routing 和 "_locale"的问题

转载 作者:行者123 更新时间:2023-12-02 07:27:54 24 4
gpt4 key购买 nike

这是我的 app/routing.yml

FrontendBundle:

resource: "@FrontendBundle/Resources/config/routing.yml"
prefix: /{_locale}/
requirements:
_locale: en|es

BackendBundle:

resource: "@BackendBundle/Resources/config/routing.yml"
prefix: /{_locale}/app
requirements:
_locale: en|es

fos_js_routing: resource: "@FOSJsRoutingBundle/Resources/config/routing/routing.xml"

这是我的 BackendBundle\Resources\Config\routing.yml

getModelsFromMake:

pattern:  /getModelsFromMake/{idMake}

defaults: { _controller: BackendBundle:Backend:getModelFromMake }
options:
expose: true

我的问题是当我像这样进行 ajax 调用时:

$.ajax({ type: "POST",

    url: Routing.generate('getModelsFromMake'),
data: {
idMake: $('#make').val(),
},
dataType: "json",
success: function(data) { console.log("All OK"); },
error: function() { console.log("ERROR"); }
});

chrome 检查员告诉我:

Uncaught Error: The route "getModelsFromMake" requires the parameter "_locale".

有解决办法吗?

编辑 1:

在我的布局中我有这个:

<script type="text/javascript" src="{{ asset('bundles/fosjsrouting/js/router.js') }}"></script>
<script src="{{ path('fos_js_routing_js', {"callback": "fos.Router.setData"}) }}"></script>

编辑 2:

如果我运行命令“php app/console fos:js-routing:debug”我得到这个:

Name              Method Pattern
getModelsFromMake ANY /{_locale}/app/getModelsFromMake

最佳答案

要将请求区域设置为您对 Routing.generate 的所有调用,您可以覆盖此方法并在每次调用中添加 {{app.request.locale}} 参数。以下脚本必须在 twig 模板中并在包含路由脚本之后执行。

<!-- Include JSRouting libs & exposed routes -->
<script src="{{ asset('bundles/fosjsrouting/js/router.js') }}"></script>
<script src="{{ path('fos_js_routing_js', {"callback": "fos.Router.setData"}) }}"></script>

<script>
$(function () {
// change name of initial method
Routing.generateImpl = Routing.generate;
// override generate fonction by adding a default _locale from request locale
Routing.generate = function (url, params) {
var paramsExt = {};
if (params) {
paramsExt = params;
}
if (!paramsExt._locale){
paramsExt._locale = '{{ app.request.locale }}';
}
return Routing.generateImpl(url, paramsExt);
}
})
</script>

现在您可以透明地使用 Routing.generate 而不必担心 _locale 参数!

// in any JS file
var url = Routing.generate('mypath');
var url2 = Routing.generate('another path', {param: 1});

为了阐明代码,可以将前面的脚本隔离在一个 js 文件中。为此,必须按照@DonCallisto 的指示定义一个全局变量。

<!-- for exemple in the <head> of the page -->
<script>
var REQUEST_LOCALE = '{{ app.request.locale }}';
</script>

因此在脚本中您可以使用 REQUEST_LOCALE

// this line
paramsExt._locale = '{{ app.request.locale }}';
// has to be replaced by
paramsExt._locale = REQUEST_LOCALE;

关于php - Symfony、fos_js_routing 和 "_locale"的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25842418/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com