Internationalization is a common task for many projects. And even if we don’t need to support multiple languages, it still can be useful to store all user messages together to have better perspective and avoid duplication.
CUBA provides the CubaLocalizeBehavior
that can assist you in this task.
Basically, it just introduces the msg()
method that gets messages from the messages
property depending on the current locale. See an example below.
<html>
<head>
<link rel="import" href="src/recipes/i18n/simple-greeting-component.html">
<script src="bower_components/webcomponentsjs/webcomponents-loader.js"></script>
</head>
<body>
<simple-greeting-component></simple-greeting-component>
</body>
</html>
link:../../../source/polymer-build/src/recipes/i18n/simple-greeting-component.html[role=include]
Result
CubaLocalizeBehavior
requires an initialized cuba-app.
How the default locale is determined is up to you: you can set a locale on component initialization or provide some kind of language switcher that changes the locale. Below is an example of switching locale.
<html>
<head>
<link rel="import" href="src/recipes/i18n/locale-switcher.html">
<script src="bower_components/webcomponentsjs/webcomponents-loader.js"></script>
</head>
<body>
<locale-switcher></locale-switcher>
</body>
</html>
link:../../../source/polymer-build/src/recipes/i18n/locale-switcher.html[role=include]
Result
Still it would be more convenient to have a single place where all messages are stored.
It can be easily achieved by creating a proxy between CubaLocalizeBehavior
and the rest of your application.
<html>
<head>
<link rel="import" href="src/recipes/i18n/calcium-adv.html">
<script src="bower_components/webcomponentsjs/webcomponents-loader.js"></script>
</head>
<body>
<calcium-adv></calcium-adv>
</body>
</html>
link:../../../source/polymer-build/src/recipes/i18n/calcium-adv.html[role=include]
link:../../../source/polymer-build/src/recipes/i18n/i18n-mixin.html[role=include]
Result
As you can see, now the components just implement I18nMixin
and don’t contain any actual messages.