18 Program to Pass Complex Data to Templates using Embedded-JS and ExpressJS

Program:

app.js:

var express = require('express');

var app = express();



app.set('view engine', 'ejs');



app.get('/home', function (request, response) {

    response.send("This is my HomePage");

});





app.get('/posts/:id', function (request, response) {

    var blog = {

        'post_title': 'Tech Post',

        'post_category': 'Tech',

        'post_author': ['CodingAtharva', 'John', 'KimJo']

    };

    response.render('blog', {

        'blog_post': request.params.id,

        'blog': blog

    });

});



app.listen(5000);


/views/blog.ejs:

<!DOCTYPE html>

<html>



<body>

    <h1> This is a Heading. </h1>

    <h1>

        <%= blog_post %>

    </h1>



    <h2> <%= blog.post_title %> </h2>

    <h2> <%= blog.post_category %> </h2>

    <h2> <%= blog.post_author %> </h2>





    <ul>

        <% blog.post_author.forEach(function(item){ %>

        <li> <%= item %> </li>

        <% }); %>



    </ul>



</body>



</html>


Output:

Pass Complex Data to Templates using Embedded-JS and ExpressJS

Previous
Next Post »