Localization of static HTML with i18next (loading local json translation files) - javascript

My project is HTML only. I am not going to use node or react version.
I've tried default example that works fine
<div id="output" />
<script src="https://unpkg.com/i18next/dist/umd/i18next.min.js"></script>
<script>
i18next.init({
lng: 'en',
debug: true,
resources: {
en: {
translation: {
"key": "Hello World"
}
},
de: {
translation: {
"key": "hello welt"
}
}
}
}, function(err, t) {
// init set content
updateContent();
});
function updateContent() {
document.getElementById('output').innerHTML = i18next.t('key');
}
function changeLng(lng) {
i18next.changeLanguage(lng);
}
i18next.on('languageChanged', () => {
updateContent();
});
</script>
but I can't figure out how to load local json files instead of placing all translations in the js. Do I have to install an additional plugin for loading json translation files?
and is this the correct way of targeting every string in HTML?
function updateContent() {
document.getElementById("homeTitle").innerHTML = i18next.t("home.title");
document.getElementById("homeSubtitle").innerHTML = i18next.t("home.subtitle");
}
is there a way to add an attribute to HTML string like
<h1 data-i18n="home.title"></h1>
to get the translation?

You could load them with fetch, running a bunch of promises.
I wrote a sandbox code example for you in vanilla JS.
PS: Don't know why, but when you open code sandbox the code isn't executed well, you have to refresh the local preview to get it working (or you could try to open the preview from here), but I tested it via Live Server in my dev environment and it's working fine.

Related

Angular *.docx and *.xlsx file free tool to preview inside the application using Library like 'ngx-doc-viewer2' or Other

It's been 3 days, I am searching for a solution to display my *.docx and *.xlxs file in my angular application. I have an API which is returning the files as blob. Now, I want to use that blob to show the file. I can easily download the file using window.open(blobLink), however, my main task was to view the file. So, I searched and found ngx-doc-viewer and it does not work with the blob link as I currently found and file needed to be publicly accessible. But, my application will run in the local network. So, how can I solve this problem. Here is my *.ts and HTML code below=>
TS
getFile(fileData: File) {
this.tempBlob= null;
this.ProposalService.getFile(fileData).subscribe(
(retFileData: any) => {
this.tempRetFileData = retFileData;
},
(err: Error) => {
},
() => {
const blob = new Blob([this.tempRetFileData], { type: this.contentType });
this.docURL = window.URL.createObjectURL(blob);
}
);
}
HTML
<ngx-doc-viewer [url]="docURL" viewer="google" style="width:100%;height:50vh;"></ngx-doc-viewer>
Note: Any other free Library and solution is acceptable.
For blob type use viewer="mammoth":
<ngx-doc-viewer [url]="docURL" **viewer="mammoth"** style="width:100%;height:50vh;"></ngx-doc-viewer>
To use mammoth, also add:
npm install mammoth --save
and make sure mammoth.browser.min.js is loaded. For the angular/cli you would add the following in angular.json:
"scripts": [
"node_modules/mammoth/mammoth.browser.min.js"
]

Simple CSV parsing in Javascript

Here is my problem:
I am trying to parse a local CSV file in JavaScript. The file looks like this:
Year,Promo,Surname,Name,Mail
2005/2006,0,XXXX,XXXXX,xxxxx.xxxxx#gmail.com
(...)
2006/2007,1,XXXX,XXXXX,xxxxx.xxxxx#gmail.com
(...)
2007/2008,2,XXXX,XXXXX,xxxxx.xxxxx#gmail.com
etc.
I tried to parse it using several librairies (PapaParse.js, jquery-csv, d3.js...), but:
either the parsing fails (my array is empty)
or I get a XMLHttpRequest cannot load - Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource error, since my file is stored locally.
Is there a simple solution to parse a CSV file in JavaScript, in order to access the data? I looked up hundreds of posts on forums but I could not get it to work.
Thank you very much (excuse me, I am quite new in JS).
Tom.
this answer is canonical in that it addresses anyone's problem that might be described by the question. Only the first of these answers is meant for the OP, although, regarding the last comment, the edit section I added at the bottom is also specifically for the OP.
if you are doing this for a small, local app, you probably can do one of these two things:
launch the browser with CORS disabled:
Chrome.exe --disable-web-security
in the source there is also instructions for firefox
src
run a micro server for your files:
If you’ve got Python installed (most Mac and Linux users do), you can start a quick local web server for testing. Using the command prompt, navigate to the directory that has your HTML files and run the following command:
python -m SimpleHTTPServer
Your files should now be accessible from http://localhost:8000/ and may have a good chance of working when file:/// does not.
src
A better solution, if you run into CORS issues with the python server, might be local-web-server from node: https://www.npmjs.com/package/local-web-server
the typical user looking for an answer to this question is probably using node:
'use strict';
var fs = require('fs');
var readFilePromise = function(file) {
return new Promise(function(ok, notOk) {
fs.readFile(file, function(err, data) {
if (err) {
notOk(err)
} else {
ok(data)
}
})
})
}
readFilePromise('/etc/passwd').then(function(data) {
// do something with the data...
})
src
edit: setting it up for a simple application:
Make the server a serivce in rc.d or wherever. Follow a guide like this: https://blog.terminal.com/using-daemon-to-daemonize-your-programs/
Don't make the server a local service that is active! Instead, make a script to launch your app, and only from that script start the daemon. In your init script for the service, write a check to look for your app's PID or something every few minutes and autoshutdown when the app is no longer running.
Here is a code sample code for basic parsing of CSV you could try.
First step: Read the file.
We can read the file content using the FileReader class method readAsText, because the content in a CSV file is just some text .
Read more about FileReader here: https://developer.mozilla.org/en-US/docs/Web/API/FileReader
This code should be in an 'async' function. Because we have used 'await' to wait for the promise to resolve or reject.
Here the file variable is the File Object you have from the file input HTML element.
const fileContent = await(() => {
const promise = new Promise((resolve,reject) => {
const fileReader = new FileReader();
fileReader.onloadend = ()=>{
try {
const content = fileReader.result;
resolve(content);
} catch (error) {
reject(error);
}
};
fileReader.readAsText(file);
});
return promise;
})();
Second step: Transforming the file.
Here I transformed the file content into an array. A 2D array containing the CSV data.
/** extract the lines by splitting the text content by CRLF */
const linesArray = fileContent.split('\r\n');
const outcomeArray = [];
for (let rowIndex = 0; rowIndex < linesArray.length; rowIndex++) {
/** Checking whether the line is empty or not.
It's possible that there is a blank line in the CSV file.
We shall process only if not blank */
if (linesArray[rowIndex].trim()) {
/** Extract the cell out of the current line */
const currentline = linesArray[rowIndex].split(',').map((cellData, columnIndex) => {
/** Forming the data as an object. This can be customised as needed */
return {
rowIndex,
columnIndex,
value: cellData?.trim()
};
});
outcomeArray.push(currentline);
}
}
Example
If we parse a CSV having this content:
10,11
20,21
Output is a 2D array as below:
[
[
{
"rowIndex": 0,
"columnIndex": 0,
"value": "10"
},
{
"rowIndex": 0,
"columnIndex": 1,
"value": "11"
}
],
[
{
"rowIndex": 1,
"columnIndex": 0,
"value": "20"
},
{
"rowIndex": 1,
"columnIndex": 1,
"value": "21"
}
],
]

pdf with 25mb size not readable in monocle reader

I just started using the monocle reader and tried using a pdf i downloaded before it has roughly 800 pages and 25mb file size, the problem now is that monocle returns with this error
TypeError: Cannot read property 'onFirstPageOfBook' of null
Resource interpreted as Document but transferred with MIME type
application/pdf
If i use a 1 page pdf it works fine.
This is my code:
<script type="text/javascript">
var bookData = {
getComponents: function () {
return [
'coolresume.pdf',
'content1.html'
];
},
getContents: function () {
return [
{title: "Chapter 1", src: 'coolresume.pdf'},
{title: "Chapter 2", src: 'content1.html'}
]
},
getComponent: function (componentId) {
return {url:componentId};
},
getMetaData: function(key) {
return {
title: "Test document",
creator: "Aron Woost"
}[key];
}
}
Monocle.Events.listen(
window,
'load',
function () {
window.reader = Monocle.Reader('reader', bookData);
}
);
</script>
the monocle
This is were i got my sample PDF, this also works fine for when the same PDF is converted to EPUB
PDF URL
PDFs may not be officially supported by monocle js: https://groups.google.com/forum/#!searchin/monocle-js/pdf/monocle-js/0ue1t243JLg/hgOPIQaramQJ
However some PDFs work and some don't. I've tracking the ones that don't down to the monocle js source code, lines 3555, 3556, 3557:
Monocle.Events.listen(frame, 'load', onDocumentReady);
Monocle.Events.listen(frame, 'load', onDocumentLoad);
frame.contentWindow.location.replace(url);
...using PDF as a source, a url value is sent to the frame.contentWindow.location.replace function, but with some PDFs the load event is not firing, therefore the previously attached functions do not execute and the script stalls with a blank page, but other PDFs load fine.
Also, when I run the monocle HTML page through the theseus debugger, the failing PDFs also load just fine.
Another point, monocle js is loading the PDFs in an embed tag. The same embed tag code loaded independently of monocle js loads just fine. And the ones that work load 2 pages, both embed tags with the same PDF url. The ones that don't work only get one embed tag implemented but not all the monocle id's are there.
It may be related to file size. I was not able to load a PDF at 555K, but 412K and lower loaded fine.
It's a nasty hack, but this loads the PDFs that won't otherwise:
//Monocle.Events.listen(frame, 'load', onDocumentReady);
//Monocle.Events.listen(frame, 'load', onDocumentLoad);
frame.contentWindow.location.replace(url);
onDocumentReady();
onDocumentLoad();

How to add a pure javascript compiler plugin server-side when running CFGroovy in Coldfusion?

I'm trying to sell myself to the idea of trying to build enhanced Jquery Mobile markup on the server (running Coldfusion8) and then try to use DustJS (Javascript templating engine) to precompile the markup into a js string, which I want to server as a static file.
I think I have it down to trying to add the plugin in Coldfusion. Here is what I want to do:
Start with a template like this in Coldfusion:
<cfsavecontent variable="renderedResults">
<cfoutput>
{##person}{root}: {name}, {age}{/person}
</cfoutput>
</cfsavecontent>
Running this through the DustJS compiler on NodeJS returns something like this:
(function() {
dust.register("demo", body_0);
function body_0(chk, ctx) {
return chk.section(ctx.get("person"), ctx, {
"block": body_1
}, null);
}
function body_1(chk, ctx) {
return chk.reference(ctx.get("root"), ctx, "h").write(": ").reference(ctx.get("name"), ctx, "h").write(", ").reference(ctx.get("age"), ctx, "h");
}
return body_0;
})();
which I then save as someStaticTemplate.js. This file is pulled in on the client and filled with dynmic data.
My problem is compiling this in Coldfusion.
I'm using Cfgroovy in order to run Javascript on the server:
<cfimport prefix="g" taglib="../../tags/cfgroovy/" />
35k zipped plugin here
<!--- COMPILE --->
var dustedTemplate = dust.compile( variables.tempLateToCompile, variables.templateName);
<!--- OUT --->
variables.put("renderedResult", dustedTemplate);
</g:script>
However doing it like this returns the following error:
type: sun.org.mozilla.javascript.internal.JavaScriptException
message: [object Error] (<Unknown Source>#1)
So I must be doing something wrong...
Question:
Is it possible at all to compile this server-side into JS? If so, any idea how to include the plugin. I have also looked at this post, but I'm already stretching what I can do, so I'm hoping this can work out as I'm trying above.
Thanks for some inputs!
BOUNTY:
Ok, I give up trying myself. Bounty time... I'm looking for a Coldfusion code snippet that allows me to
a) load the DustJS plugin in a CFGrooy tag or alternative javascript enabling setting
b) let's me run the DustJS Javascript-compile function to turn my template from
{##person}{root}: {name}, {age}{/person}
into this:
(function() {
dust.register("demo", body_0);
function body_0(chk, ctx) {
return chk.section(ctx.get("person"), ctx, {
"block": body_1
}, null);
}
function body_1(chk, ctx) {
return chk.reference(ctx.get("root"), ctx, "h").write(": ").reference(ctx.get("name"), ctx, "h").write(", ").reference(ctx.get("age"), ctx, "h");
}
return body_0;
})();
If that is not possible technically, I'm open for alternative approaches, that allow me to create a template on the server, which is HTML based and includes placeholder so I can add dynamic data on the client.
Thanks!
You should look at http://www.bennadel.com/blog/1766-Running-Javascript-In-ColdFusion-With-CFGroovy-And-Rhino.htm
and Is it possible to compile HTML markup to templatable javascript on Coldfusion server-side?
Happy Coding!!!

PDF Javascript message from PDF to HTML document is not delivered

I'm trying to get my PDF javascript embedded code to communicate to its HTML container page. But I've been able to make it work only 1 way(HTML->PDF)
Maybe the problem is that the object tag is being generated dynamically( because I need to load pdfs on-the-fly)
js in my pdf file(runs in the OPEN action):
this.hostContainer.messageHandler =
{
onMessage: function(messageArray)
{
app.alert('msg received' + messageArray);
},
onError: function(error, messageArray){ },
onDisclose: function() {return true;}
};
try{
this.hostContainer.postMessage(["never", "delivered"]); // this line doesn't work. :(
}
catch(e){
app.alert(e.message);
}
my html page js code :
function messageFunc(messageArray) {
alert('finally!!');
}
$j('#pdf_div').html("<object type='application/pdf' data='http://url.to.dinamically.generated.pdf' id='PdfObject'> </object>");
$j("#PdfObject").ready(function() {
document.getElementById('PdfObject').messageHandler = { onMessage: messageFunc };
});
As I said, the PDF can receive the messages without problems, but I'm unable to send messages from the PDF to HTML code.
Btw, I'm using JQuery.
Any help would be really appreciated.
Thanks.

Categories

Resources