Ember: dynamic switch to chosen language (using i18n library)

前端 未结 3 1274
孤独总比滥情好
孤独总比滥情好 2021-02-05 16:05

I am using the ember-i18n library for translation of static strings used throughout my application. As the language files are rather big, I do not want to load at application st

3条回答
  •  礼貌的吻别
    2021-02-05 16:31

    I have not done translations in my app yet, but I plan to do so. So I'm also interested to know what is the best solution. I will describe my current idea how I would do it with my current knowledge.

    1) I would define language as a top level route.

    App.Router.map(function() {
        this.resource('language', {path:'/language/:lang_code'}, function() {
            // All other routes
        });
    });
    

    Then changing the language would be a link to Language route with corresponding language code. I would also define Language model with attributes code, name, flag etc. for this. This would be also handy when showing list of language select buttons or dropdowns.

    Also when loading subroute model you already know what the langugage is and you can fetch the models in current language (for example think about blog post that is different in every language). Use this.modelFor('language') to get current language in any subroute.

    2) This is tricky. AFAIK there is no public API to get current URL with all the dynamic segments. There is currentPath property in application controller, but it doesn't include dynamic route variables. There are also some Ember internal variables, but I wouldn't use them as they might change. You can also investigate current router url: this.get('router.url'). Also you can bypass ember and use window.location.href to read the URL directly. But I would not spend too much time on that. Users change their language rarely (usually on first visit only) and it's not a big problem to redirect to index route on language change. I would store it in a cookie or local storage and then there is no need to change the language later. If Ember comes up with nice and easy way to do it then you can easily add this functionality later.

    3) I would not put anything into application template as it is not translated. Use language template instead of application template and then everything should re-rendered as you are switching the language.

    4) I think that the texts are not automatically updating because they are not currently two-way binded. But it is fine, because it is not a very good idea to have two way bindings for all texts as it can make system slow. So just put the language as top level route and everything should work fine:)

提交回复
热议问题