I have a javascript function in a wordpress script, I need it to be compatible with WPML chain translation
ubp_show_error("<p>Inutile de l'ajouter plusieurs fois</p>");
How can I make this chain to be something like this :
ubp_show_error(_e('<p>Inutile de l'ajouter plusieurs fois</p>','mytheme'));
I've tryed :
$error = _('<p>Inutile de l'ajouter plusieurs fois</p>','mytheme');
ubp_show_error($error);
but in javascript, this doesn't work
You need to localize your script.
PHP
function custom_load_scripts() {
wp_enqueue_script('your-script', '/your-script.js');
wp_localize_script('your-script', 'your_js_obj_name', array(
'error' => __("<p>Inutile de l'ajouter plusieurs fois</p>",'mytheme')
)
);
}
add_action('wp_enqueue_scripts', 'custom_load_scripts');
Now you have access to that data in your javascript file like:
JS
your_js_obj_name.error // --> '<p>Inutile de l'ajouter plusieurs fois</p>'
I would like to use, as I am doing now, one file for my primary language and a second file for english.
This is working great.
Now I would like to add two more files. One with just the changes compared to the primary language and a second one for the other language.
In other word..the first file is a big file with all the dictionary but for a specific customer i need some words to be translated differently. Instead of writing another file 99% equal to the original I just would like to write the different words.
How can I do that?
this is my code:
var i18nextInstance = i18next
.use(i18nextXHRBackend)
.use(i18nextBrowserLanguageDetector)
.init(
{
detection: {
// Escludo localStorage. Praticamente ricorda l'ultima lingua usata.
//order: ['querystring', 'cookie', 'localStorage', 'navigator', 'htmlTag'],
order: ['querystring', 'cookie', 'navigator', 'htmlTag'],
},
fallbackLng: 'en',
lng: lingua_attiva,
debug: false,
ns: ['common'],
defaultNS: 'common',
backend: {
loadPath: './i18n/{{lng}}/{{ns}}.json',
crossDomain: true,
parse: function (data) {
// queste 3 righe sotto mi fanno utilizzare il json che include anche la lingua.
// infatti, nel caso di un file per lingua, la lingua non andrebbe messa. Solo che ci sono delle estensioni
// come quella di PHP che la vogliono lo stesso. Per questo la lascio e la escludo.
try {
var json = JSON.parse(data); // --> { en: { ... } }
var m = Object.keys(json); // --> ['en']
return json[m[0]]; // --> { common: { ... } }
} catch (e) {
alert(e); // error in the above string (in this case, yes)!
}
},
},
},
function (err, t) {
// initialized and ready to go!
// Se in ingresso non avevo passato nessuna lingua, la imposto adesso con quella rilevata
if (lingua_attiva == undefined) {
lingua_attiva = i18nextInstance.language.substr(0, 2);
}
// Se la lingua non è tra quelle abilitate, forzo inglese
if (lingua_attiva != 'it' && lingua_attiva != 'en') {
lingua_attiva = 'en';
}
ConfiguraMainWebsite();
AggiornaTraduzioni();
}
);
// Configuro le opzioni per utilizzare jquery nelle traduzioni
jqueryI18next.init(i18nextInstance, $, {
tName: 't', // --> appends $.t = i18next.t
i18nName: 'i18n', // --> appends $.i18n = i18next
handleName: 'localize', // --> appends $(selector).localize(opts);
selectorAttr: 'data-i18n', // selector for translating elements
targetAttr: 'i18n-target', // data-() attribute to grab target element to translate (if diffrent then itself)
optionsAttr: 'i18n-options', // data-() attribute that contains options, will load/set if useOptionsAttr = true
useOptionsAttr: true, // see optionsAttr
parseDefaultValueFromContent: true, // parses default values from content ele.val or ele.text
});
You can create a new file with diffs only (this means that the keys are the same as in the common file), let's call it diffs and use i18next namespace fallback feature.
In a specific place you can use diffs namespace (which will load diffs.json file) and fallback to your common namespace for missing keys.
Since your config is already defined common as a defaultNS, all you need to do is just for the specific user change the namespace to diffs.
<div class="outer" data-i18n="diffs:key"></div>
// -----------------------------^
$(".outer").localize();
You can define the namespace for a specific region of translation
$(".outer").localize({ns: 'diffs'});
// this will call translation on the `.outer` div with a specific namespace without the need to attach it as I've showed before
I am using the Bing Speech API (with Javascript - REST API) and as a result get something like this:
[{
"lexical":"gerson de laudos médicos por meio do reconhecimento automático",
"display":"gerson de laudos por meio do reconhecimento automático",
"inverseNormalization":null,
"maskedInverseNormalization":null,
"transcript":"gerson de laudos por meio do reconhecimento automático",
"confidence":0.7618318
}]
How do I get the result is just what is transcribed? For example, I would like to output only was the text: "gerson de laudos médicos por meio do reconhecimento automático"
You can use JSON.parse to get the results,
For ex : JSON.parse(results.d).transcript, here results.d is the resultant json data you got from Bing API & transcript
Hope that helps, let me know if you need further clarification.
I said these lines:
lexical: r.lexical,
display: r.name,
inverseNormalization: null,
maskedInverseNormalization: null,
Now to take [{"transcript":" and "}], I will use Javascript.
i have a php function which returns me this code in JSON
{"0":{"title":"Dans l\u2019appartement"},"1":{"title":"A l\u2019a\u00e9roport - D\u00e9part de B\u00e9atrice"},"2":{"title":"Visite chez Jean-Louis"},"3":{"title":"Anita \u00e0 la matenit\u00e9"},"4":{"title":"Visite chez Jean-Louis 2"},"5":{"title":"H\u00e9l\u00e9na pr\u00e9sent\u00e9e \u00e0 la famille"},"6":{"title":"Chez des proches"},"7":{"title":"Soir\u00e9e souvenir avec un proche - Photos, histoires"},"8":{"title":"Douceline tenant un b\u00e9b\u00e9"},"9":{"title":"Visite chez Jean-Louis 3"},"10":{"title":"Bapt\u00eame de Alexandra - Dans l\u2019\u00e9glise"}}
and i want to manipulated in JQuery I’ve did this but it doesn’t work
$.each(json, function(item, value) {
console.log(value);
$.each(value, function() {
console.log(this.title);
});
});
any ideas thanks a lot
The first traversal using each provides you the object containing the value of title field.
So , Simply fetch the value using :
$.each(json, function(item, value) {
alert(value.title);
});
And here is the demo jsfiddle
In a Javascript file i receive this JSon string into a hidden html string:
<input id="page_json_language_index" type="hidden" value="[{"id":"label_accept_terms","fr":"En cliquant sur le bouton ci-dessous, vous accepter de respecter les "},{"id":"label_and","fr":" et la "},{"id":"label_birthdate","fr":"Anniversaire"},{"id":"label_bottom_about","fr":"\u00c0 propos de GayUrban"},{"id":"label_bottom_contact","fr":"Contactez-nous"},{"id":"label_bottom_copyright","fr":"\u00a9 2010-2013 GayUrban.Com - Tous droits r\u00e9serv\u00e9s"},{"id":"label_bottom_privacypolicy","fr":"Vie priv\u00e9e"},{"id":"label_bottom_termsofuse","fr":"Conditions d`...mon courriel"},{"id":"label_signon_twitter","fr":"Avec Twitter"},{"id":"label_slogan","fr":"LE site des rencontres LGBT !"},{"id":"label_terms_of_use","fr":"Conditions d`utilisation"},{"id":"label_title","fr":"Bienvenue sur GayUrban | LE site des rencontres LGBT !"},{"id":"label_transgender","fr":"Transgendre"},{"id":"label_username","fr":"Nom d`utilisateur"},{"id":"label_wait_create_profile","fr":"Un moment SVP, Cr\u00e9ation de votre profil en cours..."},{"id":"label_your_gender","fr":"Votre \u00eate"}]">
from MySQL database in user language (this example is in French (fr) so, i need to access in Javascript to each "id" and each value of this 'id"
Example : for the first "id"
i need to obtain on separate variables for each ID and VALUE
var label = "label_accept_terms";
and other variable
var value = "En cliquant sur le bouton ci-dessous, vous accepter de respecter les "
so i have a problem to read and affected each ID with good label and value.
Thank you for your helping !
I must point out that you've made a mistake in your HTML. You should escape the quotes to avoid breaking attributes, for example, simply replace them with apostrophe:
<input id="page_json_language_index" type="hidden" value='[{"id":"label_accept_terms","fr":"En cliquant sur le bouton ci-dessous, vous accepter de respecter les "},{"id":"label_and","fr":" et la "},{"id":"label_birthdate","fr":"Anniversaire"},{"id":"label_bottom_about","fr":"\u00c0 propos de GayUrban"},{"id":"label_bottom_contact","fr":"Contactez-nous"},{"id":"label_bottom_copyright","fr":"\u00a9 2010-2013 GayUrban.Com - Tous droits r\u00e9serv\u00e9s"},{"id":"label_bottom_privacypolicy","fr":"Vie priv\u00e9e"},{"id":"label_bottom_termsofuse","fr":"Conditions d`...mon courriel"},{"id":"label_signon_twitter","fr":"Avec Twitter"},{"id":"label_slogan","fr":"LE site des rencontres LGBT !"},{"id":"label_terms_of_use","fr":"Conditions d`utilisation"},{"id":"label_title","fr":"Bienvenue sur GayUrban | LE site des rencontres LGBT !"},{"id":"label_transgender","fr":"Transgendre"},{"id":"label_username","fr":"Nom d`utilisateur"},{"id":"label_wait_create_profile","fr":"Un moment SVP, Cr\u00e9ation de votre profil en cours..."},{"id":"label_your_gender","fr":"Votre \u00eate"}]'>
JSON.parse is the best way to convert JSON string, but it's not surpported by old IE (e.g. IE6). You can use JSON2 to make it compatible, or just simply use eval().
Aware that abuse of eval() may lead to XSS (Cross Site Scripting) vulnerability. Make sure that the JSON you're about to parse is safe (doesn't include malicious Javascript).
Here's an example to read all id:
<input id="page_json_language_index" type="hidden" value='[{"id":"label_accept_terms","fr":"En cliquant sur le bouton ci-dessous, vous accepter de respecter les "},{"id":"label_and","fr":" et la "},{"id":"label_birthdate","fr":"Anniversaire"},{"id":"label_bottom_about","fr":"\u00c0 propos de GayUrban"},{"id":"label_bottom_contact","fr":"Contactez-nous"},{"id":"label_bottom_copyright","fr":"\u00a9 2010-2013 GayUrban.Com - Tous droits r\u00e9serv\u00e9s"},{"id":"label_bottom_privacypolicy","fr":"Vie priv\u00e9e"},{"id":"label_bottom_termsofuse","fr":"Conditions d`...mon courriel"},{"id":"label_signon_twitter","fr":"Avec Twitter"},{"id":"label_slogan","fr":"LE site des rencontres LGBT !"},{"id":"label_terms_of_use","fr":"Conditions d`utilisation"},{"id":"label_title","fr":"Bienvenue sur GayUrban | LE site des rencontres LGBT !"},{"id":"label_transgender","fr":"Transgendre"},{"id":"label_username","fr":"Nom d`utilisateur"},{"id":"label_wait_create_profile","fr":"Un moment SVP, Cr\u00e9ation de votre profil en cours..."},{"id":"label_your_gender","fr":"Votre \u00eate"}]'>
<textarea id="debug-console" cols="50" rows="20"></textarea>
<script type="text/javascript">
var arr = eval(document.getElementById("page_json_language_index").value),
output = document.getElementById("debug-console");
//output all id
for(var i=0; i<arr.length; i++)
output.value += [i, ": ", arr[i].id, "\n"].join("");
//show the first id
alert(arr[0].id);
</script>
Actually you can directly output JSON to Javascript.
To meet your needs, I think here's what you need.
<?php
...
$data = ...; //for example, from mysql query results
$language = "fr"; //you can replace it with it/en/zh...
...
?>
<input id="some_id"></input>
<script>
(function() {
var i18n = "<?php echo json_encode($data); ?>",
lang = "<?php echo $language; ?>", //language
data = eval(i18n); //you can also use JSON.parse/jQuery.parseJSON ...
for(var i=0; i<data.length; i++) {
document.getElementById(data[i].id).value = data[i][lang]; //a general way to read object's attribute in Javascript
}
})()
</script>
i need to obtain on separate variables for each ID and VALUE
This is not the way to go, you don't want to pollute your scope with a bunch of variables. What you have is a collection (array of objects). You can loop such collection and access the properties you need.
var input = document.getElementById('page_json_language_index');
var data = JSON.parse(input.value); // collection
the goal is to assign to each pair of (id, fr) value into a jquery
label
var label = function(lab) {
return '<label id="'+ lab.id +'">'+ lab.fr +'</label>';
};
var labels = data.map(label);
You can also make it a jQuery collection:
var $labels = $(labels.join(''));
Then you can append it to any container:
$labels.appendTo('body');