threxx
threxx

Reputation: 1243

NodeJS: Dynamically create html from an object

I am working with an API where I get content in form of an object in NodeJS. This object has a title, text and several tables. Now I want to iterate over this object, create HTML out of it and pass it on to my DB. In basic JS I would simply go over the objects element and create the HTML elements one by one with "document.createElement(..)". However, as I found out "document" is not available in NodeJS.

So I was wondering if there is a similar way of doing this? I saw options where I just use string e.g.: var elem = '<div>' + text + '</div>';. However, I was wondering if there are other, prettier options to handle this.

Upvotes: 2

Views: 4640

Answers (2)

JaffaLover
JaffaLover

Reputation: 11

I have a solution for you. With this method I'm ignoring the DB as you have many methods to update/retrieve data from there.

You can use ejs to update the data you render in your "html" file.

It is worth noting at this early point I am also using express to serve my frontend, if you cannot use this for whatever reason this solution won't work for you.

Html is in quotes here because the first step with ejs is to copy your html file and place it in a folder named "views" (This is the folder ejs looks for your files by default) then you rename your file to ".ejs" and add a placeholder wherever you want dynamic data.

For example your "index.html" file becomes "index.ejs" and is now placed a the newly created top level folder "views".

Placeholder looks like this:

<%= YourVariableNameHere &?> 

Then in your js file you will need to add this line below after your deceleration of app.express();

app.set('view engine' ,ejs');

Then within your app.get("/", req,res) => {... you want to add the following line:

res.render('index.ejs', {YourVariableNameHere :"Placeholder Default Message"});

This will render your default message when your page first opens. Now within your app.post methods you can re-use the res.render after figuring out what you want to display and use it to update and dynamically change what is shown on the front end.

You could build strings for display or pass string variables into the "Placeholder Default Message". It is also worth noting that html and newlines "\n" can also be passed here but to get it to render correctly in browsers you need to add style="white-space: pre; text-align: center;" either as css or as a tag.

Upvotes: 1

yunzen
yunzen

Reputation: 33439

jsdom has the solution

jsdom is a pure-JavaScript implementation of many web standards, notably the WHATWG DOM and HTML Standards, for use with Node.js. In general, the goal of the project is to emulate enough of a subset of a web browser to be useful for testing and scraping real-world web applications.

Upvotes: 1

Related Questions