How can get a normal array without quote after being placed in html dataset - node.js

I am using express js on my server and ejs as a template engine.
After getting array from my database, I send it to ejs, I then store the data in a dataset in the ejs, while trying to get the dataset using vanilla javascript, I realized that the dataset has stringify my array... How can I get it back as an array?
//ejs
<div class="news_grid" data-kkk="<%=newsData%>">
let a = document.querySelector(".news_grid").dataset.kkk

Make sure the template variable is a properly formatted JSON string, eg, when rendering:
newsData: JSON.stringify(newsData)
Then, in your frontend JS, parse the dataset into an object first:
const newsData = JSON.parse(document.querySelector(".news_grid").dataset.kkk);
// do stuff with newsData.a

Related

Body is not getting parsed in GET method

I am using mockoon for API simulation. I created 2 routes there with method GET and its body contains(responds with) JSON object. I noticed that my express app is not able to parse one of the routes. But the route that has JSON object in body which contains ARRAY is getting parsed. I tested both routes with Express(by console.log) and in chrome browser(I have JSON formatter extension) and it is behaving the same meaning response that does not contain ARRAY is not getting parsed but the response with array is getting parsed(behaving normally). Let me show the screenshots:
Express(by console.log):
With array:
Without array:
Chrome(JSON Formatter extension):
With array(extension is able to parse):
Without array(extension is not able to parse):
I tried adding Header(Content-Type: application/json) to the route in mockoon. But still, I am not aware of what is going on here. Someone please explain
The express code:
const iabs_client = await axios.get(
"http://localhost:3001/iabs-client
);
Here is the route created in Mockoon(without array inside JSON):
P.S mockoon is a program that creates endpoints in localhost, useful for API simulation when developing front-end without having backend yet
The trailing comma after "something" is not valid JSON. Edit your Mockoon body to remove the comma and it should work.

Using i18n + handlebars in an express app, but not to generate output html, how to localize?

I have an Express app in which I want to use handlebars to generate localised templated emails to be sent out. The problem is that handlebars requires a globally registered helper to translate items inside the .hbs files, while I need to use a construct such as app.use(i18n.init) to make sure my __ function translates according to the right locale in the context of the current request. Setting a locale globally will lead to concurrency issues.
The only 'solutions' (which aren't because they don't solve my problem) I found consist of using handlebars middleware to output html using Express, but that is not what I want to do. I want to generate content that's completely independent from what Express sends back to the client.
This is what I am currently doing, which obviously isn't the way to do it
const i18n = require("i18n")
const Handlebars = require('handlebars')
i18n.configure({
directory: './i18n',
defaultLocale: 'en',
objectNotation: true,
syncFiles: true
})
Handlebars.registerHelper('i18n',
function (str) {
if(!str) return str
return i18n.__(str)
}
)
to be used as
<td>
{{i18n "title"}}
</td>
A possible solution is to do the translations in code by calling i18n.__({phrase: "someText", locale: locale}) but I would like to keep this inside the template.
How can I make sure handlebars uses the i18n instance bound to the Express response object?

Jade loading a JSON file and assigning to variable

I have a JSON file in the same folder as the jade template.
Is there a way I can load the contents of the JSON file and assign it to a variable? (FYI - I am trying to do this outside of node.js passing render parameters, I am trying to get this accomplished within jade file itself)
I tried the code below and it does not work. Any pointers?
script.
var jsonValue = include ./demo_options.json
Within the jade, you can not load data, you can load in your node.js app;
var data = require('/path/to/your/demo_options.json');
//
res.render('page', {data: data});
And in your script you can use as follow:
.script
var jsonValue = #{ data }; //this part not sure if it will work

Assign jade variable to Angular

In my application, I'm using NodeJS, Express in the backend and Angular in the frontend. I'm also using Jade template engine.
jade obtains a variable called "adv" by this code.
res.render('page',{adv:result[0]})
In controller.js (for angular)
$scope.content = [];
I would like to do something like
form(ng-init="content=#{adv}")
h5 {{"content" + content}}
i.e. assign that jade variable to the scope. It is not working. I could use http.get and get the content directly to angular scope, but just wondering if it is possible to do this
Thanks
This worked.
- var str_adv = JSON.stringify(adv)
form(ng-init="content = #{str_adv}")
or even (where getContent is a function defined in controller doing the same thing)
form(ng-init="getContent(#{str_adv})")
Both these also parsed the string and stored the object in 'content'
But directly using
form(ng-init="content = JSON.stringify(#{adv})")
gives the same error
It seems assigning objects in ng-init is not possible.
Thanks #ivarni for the hint about stringify

Compile Jade to JSON?

Odd idea, but looking for the simplest approach to define some data files in Jade, and then directly convert them to JSON.
I looked at extending Jade to support a custom doctype, but quickly got lost in the code. For example:
doctype json
Only manual hacky approach I could come up with is convert the Jade to an XML file with jade, and then using better-require to read the XML file in node as an object, and then JSON.stringify the object (yikes)
If you want to use data/JSON in jade, instead of defining some data inside jade, you can pass json directly into response via response.locals or when returning response.render(view, [locals], callback) from node.
In your app.js
res.local.data=JSON.stringify(dataobj);
//or pass variable when rendering
res.render('/index', {
data : JSON.stringify(dataobj)
});
In your jade
function yourfunc(){
var data = !{dataobj};
}
This is dynamic, you can control the variables you are sending into the file, unlike statically defining them in jade.

Resources