Willem van der Veen
Willem van der Veen

Reputation: 36660

Navigation using express and EJS

Having a issue figuring out how to navigate between EJS pages effectively:

File directory:

enter image description here

I want to go from my index.ejs page to the about.ejs page. This is the code for my index.ejs page which is currently not navigating properly:

index.ejs:

<!DOCTYPE html>
<html>
  <head>
    <title></title>
  </head>
<body>
<h1> <a href="about.ejs"> This is a link to about page</a></h1>
</body>
</html>

app.js server:

const express = require("express");
const path = require('path');
const app = express();

app.set("views", path.resolve(__dirname, "views"));
app.set("view engine", "ejs")

app.get("/", (req, res) => {
res.render("index")
});

app.use(express.static('public'));

app.listen(3000);

What could I enter in the href to properly reference the dynamic about.ejs file? I already know that I can reference static files from my public folder but I want to refernce the dynamic ejs folder. If not possible any solution which provides the same functionality will also do.

Upvotes: 1

Views: 6269

Answers (4)

antzshrek
antzshrek

Reputation: 9953

Notice the correction in your index.ejs at line 7

<!DOCTYPE html>
<html>
  <head>
   <title></title>
  </head>
<body>
  <h1><a href='/about'> About</a></h1>  //there's no point including the ".ejs" extension at the end of the "about"
</body>
</html>

In your app.js server, also notice the addition of the (about route).

const express = require("express");
const path = require('path');
const app = express();

app.set("views", path.resolve(__dirname, "views"));
app.set("view engine", "ejs")

app.get("/", (req, res) => {
res.render("index")
});

app.get('/about', (req, res)=>{    //here you can include a new "about" route that should take you to the "about" page
    res.render('about')
});

app.use(express.static('public'));

app.listen(3000);

Upvotes: 0

Sagar Jajoriya
Sagar Jajoriya

Reputation: 2375

You need to create a route for your about page

app.get("/about", (req, res) => {
    res.render("about")
});

And remove the extension from the hyperlink. The hyperlink should be :

<a href="/about">About</a>

Upvotes: 1

yBrodsky
yBrodsky

Reputation: 5041

Your link should point to /about. Then you have to options. 1) have a function in your server to serve that page. 2) serve your pages dynamically.

1.

app.get("/about", (req, res) => {
  res.render("about")
});

2.

app.get("/:page", (req, res) => {
  res.render(req.params.page);
});

Upvotes: 1

alexmac
alexmac

Reputation: 19617

You should render about.ejs template to use it on the client. To do that, you need to create a new route:

app.get("/about", (req, res) => {
  res.render("about");
});

To open it use /about path.

Upvotes: 2

Related Questions