2

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.

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

Hi @Omkar, Thank you very much. I got it working using ejs .

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.