I'm currently implementing multiple languages into a web app using ember-i18n and am looking for a way in which visitors and users can choose which language they want at any time.
I'm following a tutorial found here, creating a drop down menu which toggles the content's language on the web page that the menu is on. It manages to toggle the page's language without refreshing.
However, when I navigate to a new page or refresh the current one, the language reverts back to the default.
How can I configure the web app so that the selected language remains active while navigating the site? Do I need to add something extra like including cookies?
The menu and the current environment is setup is as follows:
config/environment.js
module.exports = function(environment) {
var ENV = {
...
i18n: {
defaultLocale: 'en'}
};
...
}
}
app/app.js
App = Ember.Application.extend({
locale: 'es',
...
});
app/components/language.js
import Ember from 'ember';
export default Ember.Component.extend({
i18n: Ember.inject.service(),
classNames: ['language-select'],
locales: Ember.computed('i18n.locale', 'i18n.locales', function() {
const i18n = this.get('i18n');
return this.get('i18n.locales').map(function (loc) {
return { id: loc, text: i18n.t('language-select.language.' + loc) };
});
}),
actions: {
setLocale() {
this.set('i18n.locale', this.$('select').val());
}
}
});
app/templates/components/language-select.hbs
<select {{action 'setLocale' on='change'}}>
{{#each locales as |loc|}}
<option value="{{loc.id}}" selected={{is-equal loc.id i18n.locale}}>
{{loc.text}}
</option>
{{/each}}
</select>
app/helpers/is-equal.js
import Ember from "ember";
export default Ember.Helper.helper(function([leftSide, rightSide]) {
return leftSide === rightSide;
});
app/index.hbs
...
<p>{{language-select}}</p>
...
Additionally, I have my locales.
This answer applies to versions 1.13 through at least 3.x.
The easiest way to have state survive a page refresh is to use routing query params, which live in the URL. Each route can read from those query params or change them. When you refresh, the url stays the same.
You can read more about Query Params in The Guides.