Engine
Engine

Reputation: 5420

rendering in nodejs using express to html

I'm trying to get values from nodejs into HTML. I've seen lot of answers, but none of them is working.

here what I've done so far:

index.html

    <!DOCTYPE html>
<html>
<head>
    <meta charset='utf-8'>
    <meta http-equiv='X-UA-Compatible' content='IE=edge'>
    <title>Page Title</title>
    <meta name='viewport' content='width=device-width, initial-scale=1'>
    <link rel='stylesheet' type='text/css' media='screen' href='main.css'>

</head>
<body>

    <div> 
          <a id="test" name="test"> <%=name%></a>


    </div>
</body>
</html>

app.js

   const express =require('express')
const app = express();
var os = require( 'os' );
var path = require('path')
const PORT = process.env.PORT ||2000;


app.engine('html', require('ejs').renderFile);

app.get('/',(req,res)=>{
    res.sendFile(path.join(__dirname+'/index.html'))
})


app.get('/test', (req, res)=> {

    var name = 454;

    res.render( "/index.html", {name:name});

  });

app.listen(2001) 

I don't get what I'm doing wrong. but it doesn't work as expected. any idea how may I solve this ? thanks in advance !

Upvotes: 1

Views: 56

Answers (1)

pzaenger
pzaenger

Reputation: 11973

First, create a folder views and put your index.ejs right there (though, I am not sure, the extension have to be .ejs).

Then set the engine with:

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

And change your routing to:

app.get('/', (req,res) => {
    res.render('index', { name: 'Test' });
});

Edit: I have used the express application generator and also checked Using template engines with Express.

Edit: According to the extension .ejs:

One thing to note is that all files in which ejs syntax are used in must be saved with a .ejs extension [...]

Taken from Using EJS as a Template Engine in your Express App, not from the official docs.

Upvotes: 2

Related Questions