Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing data from Node js to HTML using EJS

Here's my Server Side code:

app.set('view engine', 'html');
app.engine('html', require('ejs').renderFile);
app.use(express.static('views'));
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());

app.get('/',function(req,res){
    var title = "PERFORMANCE OVERVIEW";
    res.render('Main.html',{name:title});
})

Here's my Client Side code(Main.html):

<div class="row">
    <div class="sm-col-12">
    <h3 contenteditable="true" style="font-family:BentonSans Medium; text-align:center; color:rgb(0,38,99);"><%= name %></h3>                    
    <hr style="border-top: dotted 2px;color:grey" />
    </div>
</div>

The output I am getting on Main.html Page is "<%-name%>". Instead, it should print "PERFORMANCE OVERVIEW". What exactly wrong in this code?

Edit:

I forgot to mention that I have also tried other variants like <%= name%> and {{ name }}. But I am getting the output "<%= name%>" and "{{ name }}" respectively.

like image 937
Harsh kumar Avatar asked Jan 27 '23 15:01

Harsh kumar


1 Answers

changing it to <%= name %> should fix it.

If that doesn't you can try changing app.set('view engine', 'html') to app.set('view engine', 'ejs');, then deleting the following 2 lines.

app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());

app.get('/',function(req,res){
    var title = "PERFORMANCE OVERVIEW" ;
    res.render('Main',{name:title}) ;
});

I have always written it this way, so I can't say for sure if you syntax is correct, or if ejs will even work without setting it like this.

Update

Make sure the Main.html file is in a folder called views, and rename this file to Main.ejs.

next change res.render('Main.html',{name:title}); to res.render('main',{name:title});

like image 182
Lord Elrond Avatar answered Jan 29 '23 22:01

Lord Elrond