Using ejs with Node.js and Express
Hello , in this article i’ll show you how to add js code into html using ejs with Node.js express framework.
Ejs is an html template.Html into easy js code.You can simply embed js code in html.Just as we can write php code in html. Since it is a module, you need to install it. You can install npm install ejs in the folder where your project is located.
When encoding on Express, pages with the extension .ejs are generally kept in the Views folder. In the example I have written, I have carried out such transactions.
We need to create our files as index.ejs, not index.html. There are many templets on the market, but express normally uses jade templete, but in my opinion, ejs is a more successful and legible templete.
See the example I wrote below.
- app.js
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
var express = require('express'); var ejs = require('ejs'); //ejs.open = '*'; //ejs.close = '**'; var app = express(); app.engine('.ejs', ejs.__express); app.set('views',__dirname+'/views'); app.get("/", function(req,res) { res.render('./index.ejs', { title: 'My site', name: 'taha sivaci', site: 'tahasivaci.com', data: {bio:'bla bla bla...',twitter: '@tahasvc', instagram: '@taha.svc'} }); }); app.listen(8000,function(){ console.log("Server started! port:8000"); }); |
- index.ejs
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
<!DOCTYPE html> <html> <head> <title><%- title %></title> </head> <body> <style media="screen"> .s-div { width: 150px; height: auto; background-color: #eee; border-radius: 5px; } .s-div > span { display:block; width:100px; height: 100%; margin: 0 auto; color:green; font-weight: bold; } </style> <h1>Name -> <%- name %></h1> <h2>Site -> <%- site %></h2> <div class="s-div"> <span><%- data.bio %> </span><br> <span><%- data.twitter %> </span><br> <span><%- data.instagram %> </span><br> </div> <ul> <% for(var i = 0;i<3;i++){ %> <li><%- i %></li> <% } %> </ul> </body> </html> |
The use is quite simple as you can see. You can call other pages on the page <% – include (‘header order) -%> and write your site modularly. If you wish, you can change the opening and closing signs according to yourself.
See ejs doc for more.
Recent Comments