最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to pass locale using FOSJsRoutingBundle - Stack Overflow

programmeradmin3浏览0评论

I installed FOSJsRouting but my route need _locale parameter. How can I do that in JS ? Is there a way to get the locale in js ?

In twig, I can do app.request.attributes.get('_locale') but in JS, I don't find any documentation.

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(){
    }
});

I installed FOSJsRouting but my route need _locale parameter. How can I do that in JS ? Is there a way to get the locale in js ?

In twig, I can do app.request.attributes.get('_locale') but in JS, I don't find any documentation.

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(){
    }
});
Share Improve this question edited Jun 20, 2020 at 9:12 CommunityBot 11 silver badge asked Apr 29, 2015 at 7:31 Benjamin LucasBenjamin Lucas 3805 silver badges20 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 8

What I usually do is set the locale as a html-tag attribute

<html lang="{{ app.request.locale }}"> 

which results in

<html lang="EN">

This is also useful for SEO, and you can always get the locale in JS by calling

$('html').attr('lang');

If your Js scripts is in twig, you can do something like that :

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(){
    }
});

You can also use the master version of FOSJsRoutingBundle which includes a PR that makes the _locale parameter injected automatically.

Update your poser.json file with:

"friendsofsymfony/jsrouting-bundle": "dev-master"

And run:

poser update friendsofsymfony/jsrouting-bundle

I don't like using master versions of libraries, but that is the easiest solution for now.

发布评论

评论列表(0)

  1. 暂无评论