polymerelements / app-localize-behavior Goto Github PK
View Code? Open in Web Editor NEWPolymer behaviour to help internationalize your application
Polymer behaviour to help internationalize your application
Could you add support for
?
The pathToResources
property is unused
The element use the path to load ressources from the behavior.
It seems that the property does not work.
I will fix this and I will propose a PR to fix this issue.
localize throws an error when the resources for a language have not been loaded
the same result as when resources are not loaded, or language is not set (return undefined)
Error: Cannot read property 'greeting' of undefined
x-translate.<anonymous> at /components/app-localize-behavior/app-localize-behavior.html:214
x-translate._annotatedComputationEffect at /components/polymer/polymer.html:1642
x-translate._effectEffects at /components/polymer/polymer.html:1449
x-translate._propertySetter at /components/polymer/polymer.html:1433
x-translate.__setProperty at /components/polymer/polymer.html:1442
x-translate._computeEffect at /components/polymer/polymer.html:1629
x-translate._effectEffects at /components/polymer/polymer.html:1449
x-translate._propertySetter at /components/polymer/polymer.html:1433
x-translate.setter at /components/polymer/polymer.html:1512
Context.<anonymous> at basic.html:138
We just started the migration to 2.0 after rc2. Want to move completely to 2.0 as we are in early stage.
For app-localize-behavior not sure what is the best way to use in 2.0. Found #70 but that code was not fixed. Will this be available as class expression at some point or any other alternative?. For now we have a hack to just keep instance of app-localize-behavior and redirect localize method to it. And we ran in to following issue:
Could we get a fix for this.fire in following code for 2.0 branch.
__onRequestResponse: function(event) {
this.resources = event.response;
this.fire('app-localize-resources-loaded');
},
__onRequestError: function(event) {
this.fire('app-localize-resources-error');
}
Error:
Thanks.
How to detect user language in the browser using either:
This should be part of the Localize system i feel. I cant see this currently
Why this behavior using private properties and loadResources
function without prefix _
?
I include this behavior to every page element.
https://github.com/StartPolymer/progressive-web-app-template/blob/master/src/app-pages/app-page-404/app-page-404.html
It would be useful to add the possibility to customize the header that is sent when loading resources.
We are managing our translations using a translation service that expects an authentication token. So this would allow us to easily send those tokens.
The computed property localize doesn't work inside a dom-if template.
The message is displayed.
The message is not displayed.
In your demo x-translate.html
just insert
<template is="dom-if" if="[[test]]">
Test<div>{{localize('sale', 'start', 150, 'time', 15, 'price', 10)}}</div>
</template>
Polymer({...
test: {
type: Boolean,
value: true
}
...});
Test
is displayed but the message is not displayed.
Is this still required ?
Note that if you're on a browser that does not natively support the Intl object, you must load the polyfill yourself. An example polyfill can be found here.
Seems like the core libraries are not being maintained anymore and it doesn't look like yahoo is interested in keeping the project alive. Maybe it's time to move on to something else, like https://www.i18next.com/?
I actually develop an application and I use the app-localize-behavior.
The fact is I want to check the user browser language to translate with it, but if this language is not in the dictionary, it does not work.
The proposal here is to create a new property defaultLanguage
to be sure that even if the language
property is not in the dictionary the defaultLanguage
will be applied.
It is easy to extends the behavior but I do not think that I am the only to need it, so it should be great that the element implements it.
If I understand correctly, when an app has multiple pages that use app-localize-behavior, each one needs to specify the language and call this.loadResources to load a translation file. I want to specify the language once for every use of app-localize-behavior in my app and call this.loadResources once.
I can specify the language and the path to the translation file once and all uses of app-localize-behavior take advantage of those.
I have to specify these things in every usage of app-localize-behavior.
all
Hello everyone,
I just encountered that the app-localize-behavior is not working together well with a paper-dropdown-menu.
Example:
<paper-dropdown-menu>
<paper-listbox class="dropdown-content" selected="0">
<paper-item>{{localize('ByTitle')}}</paper-item>
<paper-item>{{localize('ByRelease')}}</paper-item>
<paper-item>{{localize('ByRating')}}</paper-item>
<paper-item>{{localize('ByRuntime')}}</paper-item>
</paper-listbox>
</paper-dropdown-menu>
The paper-dropdown-menu itself is working, but no text is visible although the first element is selected. When opening the listbox, all translated entries appear.
So i guess this is a timing issue and the translations are rendered "too late" to appear as selected text in the dropdown-menu, right?
Is there any way arround this issue without "breaking" the default way polymers works?
Regards,
Michael
There's the lang
standard HTML DOM property that maps to the lang
standard HTML attribute.
Why not comply to these standards?
Benefits:
lang
property already reflects to the attribute).How do you process a longer JSON string with new lines in it?
gets escapes, \n or \n\n do nothing or break, tried
to wrap the localize placeholder, didn't work either. Only way I see is to split the resource into smaller ones, which is not quite OK.
I guess "intl-messageformat" has been bundled in build file
therefore browser can not call SourceMap.
Example : Failed to parse SourceMap: http://localhost:8080/src/intl-messageformat.min.js.map
Sorry to Problem.
I can't minify app-localize-behvaior
anymore.
Minification should work.
An error is thrown saying it expects :
but found (
instead.
This is because the format.js
library returns different things for french on Chrome vs Edge. Demo: http://jsbin.com/kubarih/edit?html,console
Chrome:
"Your french total is 10,00 $US"
Edge:
"Your french total is 10,00 $"
As title says; We are loading the translation resource file from a secured endpoint. Now I have to override the loadResources function to set ajax.withCredentials = true; Please add a withCredentials option to this function.
Hi, hope this is useful.
The sample code copied as it is throws the error:
Uncaught (in promise) Error: A value must be provided for: name(…)
After i while i found out i needed to add a parameter to localize()
localize('hello', 'name', 'Batman')
This way the behavior works
There are several small errors in the documentation of this element.
Just one example:
</script>
</script>
I will fix this errors and I will propose a PR soon to fix this issue.
The localize()
function does not return nothing if the key cannot be matched in the resources object.
It is better to return the original key in the original language. It is always better to have a string in English (if it is the original language) than no string.
Returns empty string or null (not sure).
Just pass some random string to localize()
.
Tested on:
I have a project with quite a lot texts to translate. When I have hundreds of keys, it is very hard to find what text represents what key. It would be nice to have a setting that does not translate the keys, but shows the keys itself in the app.
Currently, only one resource file can be used per element, the problem with this is that simple text like "Yes", "No", "Cancel" must be added to all translation files.
Ideally, the loadResources method should allow to pass an array of paths and merge the result in the resources property.
this.loadResources([this.resolveUrl('my-element.json'), this.resolveUrl('shared.json')]);
Creating a mixin/behavior to be extended by multiple elements, the this.loadResources('/src/locales.json')
is not setting the resources
property, so this.localize('res.key')
returns undefined
resources
being set with the object in the json file
resources
stays undefined
formats-behavior.html
<link rel="import" href="../../bower_components/app-localize-behavior/app-localize-behavior.html">
<script>
FormatMixin = function(superClass) {
return class extends Polymer.mixinBehaviors([Polymer.AppLocalizeBehavior], superClass) {
constructor() {
super();
this.loadResources(this.resolveUrl('/src/locales.json'));
}
static get properties() {
return {
language: {
value: 'es'
},
formats: {
type: Object,
value: function() {
return {
number: { MXN: { style: 'currency', currency: 'MXN' } }
};
}
}
}
}
getLabel(a) {
var args = Array.prototype.slice.call(arguments);
var prop = args.join('');
var label = prop;
if(this.localize)
label = this.localize(prop);
return label;
}
}
}
</script>
then in file legal-docs.html
<link rel="import" href="mixins/formats-behavior.html">
<dom-module id="legal-docs">
<template>
<div>[[getLabel('app.title')]]</div>
</template>
<script>
class LegalDocs extends FormatMixin(Polymer.Element) {
static get is() { return 'legal-docs'; }
}
window.customElements.define(LegalDocs.is, LegalDocs);
</script>
</dom-module>
and locales.json
{
"es" : {
"app.title" : "Doctos. Legales"
}
}
I have debugged it and the constructor is being called, the json file is being loaded, confirming in the network tab in the devtools. But the resource
property is not set.
I have another app with this same pattern without problems, but it is using an earlier version of Polymer 2, so I am just guessing that something broke in recent changes.
Hello
I've set localization with AppLocalizeBehavior in my app page and result is good.
When I go to an another page (via iron-pages) then localization no longer works. I don't convert from js , only in template ex : {{localize('my-key')}}.
I've set a console log in localize function and no message appears : function is not called.
My page contains the behavior of course...
Any idea ? Path limitation (I pass from / to /test).
Many thanks
Hi :)
Localization behavior is working fine for me, but i don't know if i can use it in a ready function and how.
For exemple, for a login form, i want to show a toast with different informations in two language.
If login are good : {{localize('login_succeeded', 'pseudo', event.detail.response.pseudo)}}
If login are wrong : {{localize('login_failed')}}
If error : {{localize('login_error')}}
My code :
<div class="container flex-center-justified flex-center-align">
<div class="inner-container">
<img src="../images/myApp.png" alt="myApp">
<h2>myApp</h2>
<form is="iron-form" method="post" action="../API/v1/index.php/login" id="loginForm">
<paper-input type="text" name="pseudo" label="{{localize('login_pseudo')}}" no-label-float required></paper-input>
<paper-input type="password" name="password" label="{{localize('login_password')}}" no-label-float required></paper-input>
<paper-button noink on-tap="_submit">{{localize('login_submit')}}</paper-button>
<div class="output"></div>
</form>
</div>
</div>
<paper-toast id="toast"></paper-toast>
</template>
<script>
Polymer({
is: 'my-login',
behaviors: [
Polymer.AppLocalizeBehavior
],
properties: {
language: {
value: 'fr',
type: String
}
},
attached: function() {
this.loadResources(this.resolveUrl('locales.json'));
},
ready: function() {
var loginForm = this.$.loginForm;
var request = loginForm.request;
var toast = this.$.toast;
loginForm.addEventListener('iron-form-response', function(event) {
console.log("Form Error: ",event.detail.response.error);
if (event.detail.response.error) {
message = localize('login_failed');
toast.show({text: message, duration: 5000});
} else {
message = localize('login_succeeded', 'pseudo', event.detail.response.pseudo);
toast.show({text: message, duration: 5000});
}
});
loginForm.addEventListener('iron-form-error', function(event) {
message = localize('login_error');
toast.show({text: message, duration: 5000});
});
},
_submit(event) {
Polymer.dom(event).localTarget.parentElement.submit();
}
});
</script>
locales.json
{
"en": {
"login_succeeded": "Greetings {pseudo} !",
"login_failed": "Incorrect IDs.",
"login_error": "Oops, an error occurred !",
"login_pseudo": "Nickname",
"login_password": "Password",
"login_submit": "Connection"
},
"fr": {
"login_succeeded": "Salutations {pseudo} !",
"login_failed": "Identifiants incorrects.",
"login_error": "Oups, une erreur est survenue !",
"login_pseudo": "Surnom",
"login_password": "Mot de passe",
"login_submit": "Connexion"
}
}
Thanks.
Greetings Loïc.
So first off, I'm fairly new to Polymer and its documentation system, but I noticed that between this
PR: #55,
this code: https://github.com/PolymerElements/app-localize-behavior/blob/master/app-localize-behavior.html#L247-L251
and this documentation: https://elements.polymer-project.org/elements/app-localize-behavior?active=Polymer.AppLocalizeBehavior#method-loadResources
That the events
on the documentation haven't been updated: https://i.imgur.com/RelrNad.png
Not sure how to fix this myself, but I thought i'd point it out:)
When testing the catalog I found that:
@demo
annotation.I'm defining element language by checking document.documentElement.lang
.
ready: function () {
lang = document.documentElement.lang;
if (lang == '') {
lang = 'en';
document.documentElement.lang = lang;
}
this.language = lang;
this.toggleRtl(lang);
},
resources has strings arranged according to these 2-letter codes.
{
"en": {"colors": "Colors"},
"fr": {"colors": "Couleurs"},
"ru": {"colors": "Цвета"},
"ar": {"colors": "الألوان"},
"he": {"colors": "צבעים"}
}
Works great until I load my element on a page that has a longer language definition for example lang="en-US"
, lang="fr-LU"
, or lang="zh-Hans"
.
I've worked around this by slicing out everything after the 2nd character, but there are cases where this would break translation (China, I'm looking at you)
lang = document.documentElement.lang.slice(0,2) ;
app-localize-behavior should flexibly adapt to a variety of language code formats, falling back to acceptable alternatives in resources, should they exist.
app-localize-behavior fails on language codes which don't exactly match those listed in resources, should they exist.
How do you process a longer JSON
string with new lines in it? <br/>
gets escapes, \n
or \\n\\n
do nothing or break, tried <pre>
to wrap the localize placeholder, didn't work either. Only way I see is to split the resource into smaller ones, which is not quite OK.
In IE10 (yeah, sorry), using app-localize-behavior
causes a JavaScript error:
Unable to set property 'messages' of undefined or null reference
This occurs when it tries to manipulate the prototype's __localizationCache
object on lines 204, 214 and 218. For whatever reason in IE10, this.constructor.prototype.__localizationCache
is undefined.
Note: this is not a result of a missing Intl polyfill, as I've tested with the polyfill (still fails) and by wrapping these checks in if-
statements (it works).
Localization works in IE10 as it does in other browsers.
JavaScript error:
Kind of hard to wire up a live demo since jsbin only lets you have one file and you need 2 -- one for the app, one for a custom element that uses the localize behavior.
Basically do this in element.html
:
<link rel="import" href="../polymer/polymer.html">
<link rel="import" href="../app-localize-behavior/app-localize-behavior.html">
<script>
Polymer({
is: 'test-element',
behaviors: [ Polymer.AppLocalizeBehavior ],
ready: function() {
Polymer.dom(this.root).appendChild(
document.createTextNode(
this.localize('myHome')
)
);
}
});
</script>
And then import and consume <test-element>
in your Polymer application.
app-localize-behavior
in a custom element inside your applicationI'm doing some trials with Polymers app-localize-behavior, and I'm having a hard time to find some clear documentation regarding how to use format.js's {select} Format found here.
The app-localization-behavior documentation says :
"Polymer.AppLocalizeBehavior supports the same message-syntax of format.js, in its entirety;"
But for example in the polymer docs they pass the arguments as strings:
{{localize('hello', 'Batman')}}
and in format.js docs not:
I have {numCats, number} cats.
Now the issue I'm facing is how to use the {select} Format.
The format.js docs says to use it like this:
{gender, select,
male {He}
female {She}
other {They}
} will respond shortly.
so I did this in my template:
{{localize(wir, select,
wir {we}
ich {i}
)
}}
locales.json :
{
"en" : {
"i" : "I",
"we" : "we"
},
"fr" : {
"i" : "je",
"we" : "nous"
},
"de" : {
"i" : "ich",
"we" : "wir"
}
}
The language is set by default to french "fr"
, so I expect to get "nous" as output.
The last I did, was trying to pass everything as string or just some of the arguments (all combinations) but this all doesn't helps.
For example :
{{localize('wir', select, 'wir' {we} 'ich' {i} ) }}
Instead of "nous" the full {{localize(etc..)}}
is displayed on screen.
I think the documentation should be much clearer about this.
Could you please ewxplain to me, what I'm doing wrong here?
If we have some code like:
the _setupBrowseLabel(selectedSection) - is function witch return 1 word "browse"
How we can make it workable for localization {{localize('browse')}}
The variant with [[localize(' {{ _setupBrowseLabel(selectedSection)}} ') ]] - NOT working! (
Very important thing!
There are several small mistakes in the French translation.
I will fix this mistakes because French is my mother tongue and I will propose a PR soon to fix this issue.
The documentation is explaining the following:
The main application is usually responsible for loading the localized messages and setting the current language.
Each element that needs to localize messages should also add the Polymer.AppLocalizationBehavior and use the localize method to translate strings, as shown above.
Sub-components should have language inherited and the load of locales shouldn't be needed.
This is not working as you can see in my test: https://github.com/benj13260/localize
The "language" property need to be passed to every sub-components
and
the instruction to load the locales file must be specified in each components (even if it doesn't actually load it, this command is required or the localize is not working).
Is it possible to have sub object in JSON file translations
"search": {
"search_here": "Search here Eng"
}}
Than use localization like {{localize('search.search_here')}}
Instead of regular {{localize('search_here')}}
??
Thanks
The demo in french should show the currency according the localize.
According with the Intl.NumberFormat
specification, you can set the language to format the currency, but you only can set the options of the format, not the locales attribute.
La vente commence le Jan 1, 1970 à 1:00 AM. Tout est à 10,00 $US
La vente commence le Jan 1, 1970 à 1:00 AM. Tout est à $10.00.
The documentation states that All of these elements share a common localization cache, so you only need to load translations once.
, but I am having to set the language and load resources locally in every element.
Good day!
How can I announce language and json files in one main html, and use just {{locale('something')}} or some any function in all my html files?
Many thanks for your attention!
The app-localize-behavior
should allow to read deep JSON translation resources.
Function .localize('my.deep.translation.greeting')
should output a string
The translation is not found.
Example: https://jsbin.com/nehajuconu/1/edit?html,output
{'en': {'my': {'greeting': 'hello_deep'}}}
{{localize('my.greeting')}}
hello_deep
The main
file in bower.json is missing .html
https://github.com/PolymerElements/carbon-localize-behavior/blob/master/bower.json#L37
There is a duplicated key in file locales.json
for french language.
"fr": {
"header_1": "Traduction et localisation",
"header_2": "Pluriels et les sexes",
"greeting": "Bonjour!",
"intro": "Je m'appelle {name}",
"cats": "J'ai {numCats, number} chats. Près de {pctBlack, number, percent} d'entre eux sont noirs.",
"sale": "La vente commence le {start, date, medium} à {time, time, short}. Tout est à {price, number, USD}.",
"fruit": "{num, plural, =0 {pas de pommes} =1 {une pomme} other {# pommes}}",
"bananas": "{name} {num, plural, =0 {ne} =1 {} other {}} mange {num, plural, =0 {pas de bananes} =1 {une banane} other {# bananes}} {gender, select, male {chez lui.} female {chez elle.} other {chez eux.}}"
}
"fr": {
"header_1": "Traduction et localisation",
"header_2": "Pluriels et les sexes",
"greeting": "Bonjour!",
"intro": "Je m'appelle {name}",
"cats": "J'ai {numCats, number} chats. Près de {pctBlack, number, percent} d'entre eux sont noirs.",
"sale": "La vente commence le {start, date, medium} à {time, time, short}. Tout est à {price, number, USD}.",
"fruit": "pomme",
"fruit": "{num, plural, =0 {pas de pommes} =1 {une pomme} other {# pommes}}",
"bananas": "{name} {num, plural, =0 {ne} =1 {} other {}} mange {num, plural, =0 {pas de bananes} =1 {une banane} other {# bananes}} {gender, select, male {chez lui.} female {chez elle.} other {chez eux.}}"
}
Actually we have a crash on old Safari browser (9.1) on El Capitan OS.
The localize webcomponents seems buggy on it and crash badly.
Everything is translated according to chrome / FF behaviors
http://www.francetvinfo.fr/elections/resultats/export/histograms.html#lang=en
Cause webcomponent crash because of localize on Safari 9.1 (El capitan).
http://www.francetvinfo.fr/elections/resultats/export/histograms.html#lang=en
Try to use "this.localize" for our translations.
See errors on the browser console.
As a developer it would be great if app-localize-behavior
would support loading multiple locale/json files. That would allow devs to split the locales into multiple files and prevent duplicated translations across components.
IMO that could be as achieved by having __onRequestResponse()
merge the response into the resources
object, instead of replacing it.
I'd be happy to work on a PR for that. What do you think?
Hello everyone,
I just started to use the app-localize-behavior and got stuck at the second thing I tried.
Translating a "fixed" string for sure is easy with
<div>{{localize('greeting')}}</div>
But how to translate a "variable" string containing a polymer data-binding variable?
Example in fixed language which is working:
<div>Welcome [[username]]</div>
The output is "Welcome Peter".
But how to accomplish this with app-localize-behavior? I've tried the most obvious
<div>{{localize('greeting', 'name', [[username]])}}</div>
but the output is "{{localize('Welcome', 'name', Peter)}}" and not "Welcome Peter" like expected.
As the documentation doesn't respect this use case, I'm already stuck.
Please help :)
Regards,
Michael
I have a project that has been working quite happily on Safari 9.1 using Polymer 1.7. Yesterday I upgraded Polymer to 1.8 which also pulled in a new version of the webcomponent.js polyfills and my app stopped working on Safari 9.1 with the following error:
'undefined is not an object (evaluating 'proto.__localizationCache.ajax')
This error doesn't occur when using Safari 10.0.3.
I reverted the polymer/webcomponents.js upgrade and the problem went away.
app-localize-behavior should work with the latest version of Polymer and webcomponents.js on Safari 9.1 unless you are planning to drop support for 9.1
See description above
Not possible as our app lives behind a corporate firewall
Create an application that makes use of app-localize-behavior and attempt to view that app on Safari 9.1
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.