I am trying to pass a variable from node.js to my HTML file.
app.get('/main', function(req, res) { var name = 'hello'; res.render(__dirname + "/views/layouts/main.html", {name:name}); });
You cannot use js variables inside html. To add the content of the javascript variable to the html use innerHTML() or create any html tag, add the content of that variable to that created tag and append that tag to the body or any other existing tags in the html.
If you need to call a NodeJS function (assuming it has to interact with the other server side code such as databases etc) then you can send a request, either via AJAX or standard HTTP, to the a route on the server and call that function within the route.
All the codes means that when you access to the home page, node.js will render file “index.ejs” in “views” folder. And the “title” variable will be pass to the html, the title variable’s value will be replace to the “title” in html. Now, you want to pass the array into file html, you can do the following:
There are two approaches here you can use to view data from node ( server side ) to html: 1- You could create a file in node which return data in json, then from JQuery you could do an ajax call this page and replace parts of the HTML with it. Sample code in node js:
Just type the command $npm i data-parser and the data-parser package downloads to your machine. Next, to let our code know we'd like it to use body-parser, we create the following variable at the top of the index.js file: const bodyParser = require ("body-parser");.
You can see something like: The first parameter of the get function, it is “/”, means the home page of website. All the codes means that when you access to the home page, node.js will render file “index.ejs” in “views” folder. And the “title” variable will be pass to the html, the title variable’s value will be replace to the “title” in html.
I figured it out I was able to pass a variable like this
<script>var name = "<%= name %>";</script> console.log(name);
What you can utilize is some sort of templating engine like pug (formerly jade). To enable it you should do the following:
npm install --save pug
- to add it to the project and package.json fileapp.set('view engine', 'pug');
- register it as a view engine in express./views
folder and add a simple .pug
file like so:html head title= title body h1= message
note that the spacing is very important!
app.get('/', function (req, res) { res.render('index', { title: 'Hey', message: 'Hello there!'}); });
This will render an index.html page with the variables passed in node.js changed to the values you have provided. This has been taken directly from the expressjs templating engine page: http://expressjs.com/en/guide/using-template-engines.html
For more info on pug you can also check: https://github.com/pugjs/pug
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With