Templating Engines like EJS, pug, and handlebars are very popular among developers. Today I would like to discuss EJS  and parsing data dynamically.




Installing

         npm install --save ejs

Adding Templating Engine

·        First, we need to set engine in App.js

        app.set("view engine", "ejs");
        app.set("views", "views");
 
 //define the folder where the ejs files are (views is the default one)

·        Then we need to render the file.

In the routes handler->

router.get("/", (req, res, next) => {
  const products = adminData.products;

  old one==>
  // res.sendFile(path.join(__dirname, "../", "views", "shop.html"));

  render like this==>
  res.render("shop", { prods: products, pageTitle: "Page Title" });
 /*
  rendering template engine and injecting the data(optional)
 
  shop is the file (shop.ejs). No need to include the extension
  No need of paths - we set the engine in app.js and also the views folder
  Then pass the values as an object to that file
  engines may have changed but this function won't
 
 */
});

The shop.ejs File ->

<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />

    <title><%= pageTitle %></title>    <== we can output the value
  
    </head>

we can add vanilla java script functions inside that notation

  <% if(hasProducts) { %>

      <div class="grid">
        <% for (let product of prods) {%>
        <article class="card product-item">
          <header class="card__header">
            <h1 class="product__title"><%= product.title%></h1>
          </header>
          <div class="card__image">
            <img src="/img/img.jpg" alt="A Book" />
          </div>
          <div class="card__content">
            <h2 class="product__price">$19.99</h2>
            <p class="product__description">
              A very interesting book about so many even more interesting
              things!
            </p>
          </div>
          <div class="card__actions">
            <button class="btn">Add to Cart</button>
          </div>
        </article>
        <%}%>
      </div>
      <% } else{ %>
      <h1>No Products Found</h1>
      <% }%>


//Bonus //

      How to add image in the computer to html page

      use <img src="../" > Relative path

      (don’t use src=" D://")