Why is mypartial.ejs not showing?

Viewed 779

I am trying to learn node.js with the help the book "Get programming with node.js" by Jonathan Wrexler. In chapter 10 the use of partials is explained very briefly and I am not getting it to work.

I made a nav.ejs in the partials-folder that looks like this:

<ul>
  <li>One</li>
  <li>Two</li>
  <li>Three</li>
</ul>

The layout.ejs-example in the book looks like this:

  <body>
    <header>Header</header>
    <nav>
      <% include partials/nav %>
    </nav>
    <%- body %>
    <footer>Footer</footer>
  </body>

But this gives me a syntax-error:

SyntaxError: Unexpected identifier in C:\node-projects\wandelverhalen\views\layout.ejs while compiling ejs

With the help of stackoverflow I changed the include template to:

<% include ("partials/nav"); %>

This solved the error, but it does not show the nav when I run it. And the page source shows a <nav>-tag that is empty.

I would appreciate any help.

For the sake of completeness, this is my index.js:

"use strict";

const port = 3000;
const express = require("express");
const app = express();
const homeController = require("./controllers/homeController");
const layouts = require("express-ejs-layouts");

app
  .set("view engine", "ejs")
  .use(
    express.urlencoded({
      extended: false
    })
  )
  .use(express.json())
  .use(layouts)
  .use((req, res, next) => {
    console.log(`Request made to ${req.url}`);
    next();
  })
  .get("/", homeController.sendReqParam)
  .get("/:myname", homeController.sendReqParam)
  .listen(port, () => {
    console.log(`Server is running on port ${port}`);
  });
1 Answers

You want to use <%- include ("partials/nav"); %> to render your partial. The <% is just for scripting and control-flow and produces no output, thus you are not seeing anything added to the page. Adding a - after <% will cause it to output the unescaped value of include ("partials/nav").

Related