Reputation: 274
I am new to Node.js and I am trying to pass and access a variable from Node.js to a loaded html file/template, How do I achieve this?
Here is the sample code:
test.html
<!DOCTYPE html>
<html>
<head>
<mate charest="utf-8" />
<title>Hello world!</title>
</head>
<body>
<h1>User List</h1>
<ul>
<li>Name: Name</li> <!-- how do I call the name variable here -->
<li>Age: Age</li> <!-- how do I call the age variable here -->
<br>
</ul>
</body>
</html>
myService.js
let fs = require('fs');
let path = require('path');
// How do I pass this variables to test.html
let age = 1;
let name = "this is name";
// Read HTML Template
let html = fs.readFileSync(path.resolve(__dirname, "../core/pdf/test.html"), 'utf8');
How do I pass and access the name and age variable to test.html template so that when I read the file, the value of the variable is already generated in the template.
Upvotes: 2
Views: 1361
Reputation: 1215
You can use this library handlebars.
This one is very good to deal with larger templates.
In case you have to return a single tag, you can try this
return `<ul>
<li>Name: ${name}</li>
<li>Age: ${age}</li>
<br>
</ul>`
You can also consider using this template library for node.js npm-ejs
Upvotes: 1
Reputation: 694
You need to use a express and a templating engine for this. Please refer templating engine list - https://expressjs.com/en/resources/template-engines.html
https://expressjs.com/en/starter/generator.html
Upvotes: 3