如何使用 FOSJsRoutingBundle 传递语言环境
How to pass locale using FOSJsRoutingBundle
我安装了 FOSJsRouting 但我的路由需要 _locale
参数。我怎样才能在 JS 中做到这一点?有没有办法在 js 中获取语言环境?
在 twig 中,我可以做到 app.request.attributes.get('_locale')
但在 JS 中,我找不到任何文档。
AJAX
$.ajax({
type : 'get',
url : Routing.generate('get_credits', {'_locale': app.request.attributes.get('_locale'), 'amount' : amount, 'monthNumber' : month }),
beforeSend : function(){
console.log('loading');
},
success: function(data){
},
error : function(){
}
});
我通常做的是将语言环境设置为 html-tag 属性
<html lang="{{ app.request.locale }}">
这导致
<html lang="EN">
这对SEO也很有用,你随时可以通过调用
获取JS中的locale
$('html').attr('lang');
如果你的 Js 脚本在 twig 中,你可以这样做:
var mylocale= "{{ app.request.attributes.get('_locale') }}"; // or {{ app.request.locale }}
$.ajax({
type : 'get',
url : Routing.generate('get_credits', {'_locale': mylocale, 'amount' : amount, 'monthNumber' : month }),
beforeSend : function(){
console.log('loading');
},
success: function(data){
},
error : function(){
}
});
您还可以使用 FOSJsRoutingBundle 的 master
版本,其中包含一个 PR,可以自动注入 _locale
参数。
更新您的 composer.json
文件:
"friendsofsymfony/jsrouting-bundle": "dev-master"
和运行:
composer update friendsofsymfony/jsrouting-bundle
我不喜欢使用 master
版本的库,但这是目前最简单的解决方案。
我安装了 FOSJsRouting 但我的路由需要 _locale
参数。我怎样才能在 JS 中做到这一点?有没有办法在 js 中获取语言环境?
在 twig 中,我可以做到 app.request.attributes.get('_locale')
但在 JS 中,我找不到任何文档。
AJAX
$.ajax({
type : 'get',
url : Routing.generate('get_credits', {'_locale': app.request.attributes.get('_locale'), 'amount' : amount, 'monthNumber' : month }),
beforeSend : function(){
console.log('loading');
},
success: function(data){
},
error : function(){
}
});
我通常做的是将语言环境设置为 html-tag 属性
<html lang="{{ app.request.locale }}">
这导致
<html lang="EN">
这对SEO也很有用,你随时可以通过调用
获取JS中的locale$('html').attr('lang');
如果你的 Js 脚本在 twig 中,你可以这样做:
var mylocale= "{{ app.request.attributes.get('_locale') }}"; // or {{ app.request.locale }}
$.ajax({
type : 'get',
url : Routing.generate('get_credits', {'_locale': mylocale, 'amount' : amount, 'monthNumber' : month }),
beforeSend : function(){
console.log('loading');
},
success: function(data){
},
error : function(){
}
});
您还可以使用 FOSJsRoutingBundle 的 master
版本,其中包含一个 PR,可以自动注入 _locale
参数。
更新您的 composer.json
文件:
"friendsofsymfony/jsrouting-bundle": "dev-master"
和运行:
composer update friendsofsymfony/jsrouting-bundle
我不喜欢使用 master
版本的库,但这是目前最简单的解决方案。