dynamic fetch of localized strings from the server react-native - javascript

I want to make react-native app multilingual I use react-native-localization library and i use for JSON formats to store translations.
my question is it possible to change JSON strings dynamically for example by adding new language or changing the translation already exist

The feature you can use is Code Push here you will be updating the source JS files. if you use a dynamic JSON you will have to request it every time but using codepush you can update the source JSON itself.
More info
https://github.com/Microsoft/code-push/

You can use RN Localization setContent method, after using local strings. Check the docs:
Update / Overwrite Locale
You might have default localized in the
build but then download the latest localization strings from a server.
Use setContent to overwrite the whole object. NOTE that this will
remove all other localizations if used.
strings.setContent({
en:{
how:"How do you want your egg todajsie?",
boiledEgg:"Boiled eggsie",
softBoiledEgg:"Soft-boiled egg",
choice:"How to choose the egg"
}
})

Related

How to use multiples Parse instance

Is there a way to initialize multiple parse apps in react javascript, currently i am initializing single parse app like this
Parse.initialize(config.appId);
Parse.serverURL = config.serverURL;
Currently with the implementation of the SDK you cannot do that. Theses methods and properties are static as you can see here
What you can do is to use the REST API
You can also suggest this feature on the GitHub repository

Blue Prism: Cannot Iterate through JSON items withing injected JS script

So I am trying to iterate through JSON items via injected script. And BP is throwing me a syntax error that it is incapable of compiling my code.
code:
function fillInputs(json){
alert(json[0].Email);
}
through Invoke I am giving [JSON] variable that has a well structured JSON object which I created with help of Utility - JSON and it is working fine on test websites. But BP will not initialize specifically this part / alert(json[0].Email); / and is throwing a standard error which usually means syntax errors.
Could someone tell me if there is a better way to iterate through JSON objects with Blue Prism injected Javascript code and if I am choosing a harsh way to do it?
This is easily accomplished using the built-in Internet Explorer browser automation features provided out of the box in Blue Prism.
For organization, place your custom Javascript in a data item of type text on your action page:
Then use a Navigate stage to insert the fragment and invoke it:
With your current snippet, you'll get a nice alert window in Internet Explorer:
A good way to retrieve this data using Blue Prism would be to use the Javascript snippet you insert to create a hidden input element, the value of which is set a string representation of the JSON data you're attempting to exfiltrate.
You can then create a manual Application Modeler entry based off of an existing one to target this hidden element, and then use a Read stage to copy the data into a Data Item within Blue Prism. Further, you can use the bundled JSON object (or write your own as a wrapper around a better VB/C# library) to extract and manipulate the data within as you wish.

Internationalization in Vue.js

What are the best practices for internationalization in Vue?
Currently I'm thinking of having a 'strings' object that contains all strings, then a bit of ajax magic to update that strings object based on a json file with translated strings to certain languages.
Anyone got any better ideas? I'm currently having a bit of trouble using my strings approach since the strings object has to be loaded before anything else.
Is there a placeholder functionality for strings in Vue? For example, I have a menu whose entries reside in my vm's data. Is there a way to set that to a static string and then automatically bind that to another string once it exists?
The vue-i18n plugin is pretty good. They have documentation that follows the standard set by the Vue documentation. The package is kept up to date as well. I would start there.
One thing I like is their support for single file components. You can add an additional tag to the component with component specific translations. Here is the example from their documentation:
<i18n>
{
"en": {
"hello": "hello world!"
},
"ja": {
"hello": "こんにちは、世界!"
}
}
</i18n>
You might read this article...
I would recommend looking into a i18n lib that is ready to be used in different frameworks, i.e. i18next
There is some vue libs too: i.e. vue-i18next or #panter/vue-i18next
Further you should not only consider that you have to instrument your code (i18n) to get your app/website translated. You should think about the process too - how will you solve continuous localization, how you keep track of progress, etc...
For a translation management+ system you might eg. have a look at locize it plays well with all json based i18n frameworks... and provides a lot more than traditional systems.
Another possibility is vuex-i18n, if you want to use the Vuex store. It defines a method and a filter:
{{ 'Item' | translate }}
{{ $t('You have {count} new messages', {count: 5}) }}

What is the best way to handle i18n in an Angular app with dynamic translations

So I have been tasked with i18n on a new Angular app we are creating. I already know how to implement it if the translations are stored in json format on the client. However I have been told I cannot implement it like this as the translations will get updated on a regular basis by the client so must will have to be got from the api.
I have also been told that I cannot map directly to the json response, but instead I must create TypeScript objects which sit between the json and the UI.
What is the best way to achieve this? The header has a dropdown for languages. Do I need to call all the languages when the application loads and cache them, or do I just call each language as I need to? Do I translate only what I see on screen or does the entire app need to be translated?
do I just call each language as I need to
Definitely only the ones you need.
Do I translate only what I see on screen or does the entire app need to be translated
The relevant portions get redirected to an in memory i18n angular service that has the results cached.

Passing Python Data to JavaScript via Django

I'm using Django and Apache to serve webpages. My JavaScript code currently includes a data object with values to be displayed in various HTML widgets based on the user's selection from a menu of choices. I want to derive these data from a Python dictionary. I think I know how to embed the JavaScript code in the HTML, but how do I embed the data object in that script (on the fly) so the script's functions can use it?
Put another way, I want to create a JavaScript object or array from a Python dictionary, then insert that object into the JavaScript code, and then insert that JavaScript code into the HTML.
I suppose this structure (e.g., data embedded in variables in the JavaScript code) is suboptimal, but as a newbie I don't know the alternatives. I've seen write-ups of Django serialization functions, but these don't help me until I can get the data into my JavaScript code in the first place.
I'm not (yet) using a JavaScript library like jQuery.
n.b. see 2018 update at the bottom
I recommend against putting much JavaScript in your Django templates - it tends to be hard to write and debug, particularly as your project expands. Instead, try writing all of your JavaScript in a separate script file which your template loads and simply including just a JSON data object in the template. This allows you to do things like run your entire JavaScript app through something like JSLint, minify it, etc. and you can test it with a static HTML file without any dependencies on your Django app. Using a library like simplejson also saves you the time spent writing tedious serialization code.
If you aren't assuming that you're building an AJAX app this might simply be done like this:
In the view:
from django.utils import simplejson
def view(request, …):
js_data = simplejson.dumps(my_dict)
…
render_template_to_response("my_template.html", {"my_data": js_data, …})
In the template:
<script type="text/javascript">
data_from_django = {{ my_data }};
widget.init(data_from_django);
</script>
Note that the type of data matters: if my_data is a simple number or a string from a controlled source which doesn't contain HTML, such as a formatted date, no special handling is required. If it's possible to have untrusted data provided by a user you will need to sanitize it using something like the escape or escapejs filters and ensure that your JavaScript handles the data safely to avoid cross-site scripting attacks.
As far as dates go, you might also want to think about how you pass dates around. I've almost always found it easiest to pass them as Unix timestamps:
In Django:
time_t = time.mktime(my_date.timetuple())
In JavaScript, assuming you've done something like time_t = {{ time_t }} with the results of the snippet above:
my_date = new Date();
my_date.setTime(time_t*1000);
Finally, pay attention to UTC - you'll want to have the Python and Django date functions exchange data in UTC to avoid embarrassing shifts from the user's local time.
EDIT : Note that the setTime in javascript is in millisecond whereas the output of time.mktime is seconds. That's why we need to multiply by 1000
2018 Update: I still like JSON for complex values but in the intervening decade the HTML5 data API has attained near universal browser support and it's very convenient for passing simple (non-list/dict) values around, especially if you might want to have CSS rules apply based on those values and you don't care about unsupported versions of Internet Explorer.
<div id="my-widget" data-view-mode="tabular">…</div>
let myWidget = document.getElementById("my-widget");
console.log(myWidget.dataset.viewMode); // Prints tabular
somethingElse.addEventListener('click', evt => {
myWidget.dataset.viewMode = "list";
});
This is a neat way to expose data to CSS if you want to set the initial view state in your Django template and have it automatically update when JavaScript updates the data- attribute. I use this for things like hiding a progress widget until the user selects something to process or to conditionally show/hide errors based on fetch outcomes or even something like displaying an active record count using CSS like #some-element::after { content: attr(data-active-transfers); }.
For anyone who might be having a problems with this, be sure you are rendering your json object under safe mode in the template. You can manually set this like this
<script type="text/javascript">
data_from_django = {{ my_data|safe }};
widget.init(data_from_django);
</script>
As of mid-2018 the simplest approach is to use Python's JSON module, simplejson is now deprecated. Beware, that as #wilblack mentions you need to prevent Django's autoescaping either using safe filter or autoescape tag with an off option. In both cases in the view you add the contents of the dictionary to the context
viewset.py
import json
def get_context_data(self, **kwargs):
context['my_dictionary'] = json.dumps(self.object.mydict)
and then in the template you add as #wilblack suggested:
template.html
<script>
my_data = {{ my_dictionary|safe }};
</script>
Security warning:
json.dumps does not escape forward slashes: an attack is {'</script><script>alert(123);</script>': ''}. Same issue as in other answers. Added another answer hopefully fixing it.
You can include <script> tags inside your .html templates, and then build your data structures however is convenient for you. The template language isn't only for HTML, it can also do Javascript object literals.
And Paul is right: it might be best to use a json module to create a JSON string, then insert that string into the template. That will handle the quoting issues best, and deal with deep structures with ease.
It is suboptimal. Have you considered passing your data as JSON using django's built in serializer for that?
See the related response to this question. One option is to use jsonpickle to serialize between Python objects and JSON/Javascript objects. It wraps simplejson and handles things that are typically not accepted by simplejson.
Putting Java Script embedded into Django template is rather always bad idea.
Rather, because there are some exceptions from this rule.
Everything depends on the your Java Script code site and functionality.
It is better to have seperately static files, like JS, but the problem is that every seperate file needs another connect/GET/request/response mechanism. Sometimes for small one, two liners code os JS to put this into template, bun then use django templatetags mechanism - you can use is in other templates ;)
About objects - the same. If your site has AJAX construction/web2.0 like favour - you can achieve very good effect putting some count/math operation onto client side. If objects are small - embedded into template, if large - response them in another connection to avoid hangind page for user.
Fixing the security hole in the answers by #willblack and #Daniel_Kislyuk.
If the data is untrusted, you cannot just do
viewset.py
def get_context_data(self, **kwargs):
context['my_dictionary'] = json.dumps(self.object.mydict)
template.html
<script>
my_data = {{ my_dictionary|safe }};
</script>
because the data could be something like
{"</script><script>alert(123);</script>":""}
and forward slashes aren't escaped by default. Clearly the escaping by json.dumps may not 100% match the escaping in Javascript, which is where the problems come from.
Fixed solution
As far as I can tell, the following fixes the problem:
<script>
my_data = JSON.parse("{{ my_dictionary|escapejs }}");
</script>
If there are still issues, please post in the comments.

Categories

Resources