Andrei Daniel
Andrei Daniel

Reputation: 181

EJS/Node/Express - Having a header partial, how to change title for each page?

I recently took a course on back-end web developing.

As the title says, I don't get how can I use a header partial for the whole website but have different titles for each page. (because is included in the tag)

Is there any trick?

Upvotes: 1

Views: 3877

Answers (3)

Black Undo
Black Undo

Reputation: 1

route

app.get('/', (req, res) => {
    res.render('pages/index', {
        title: "Home Page" //this is title
    })
})

partials head

<!DOCTYPE html>
<html lang="vi">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>
     <%= typeof title !='undefined' ? title : 'Page default' %> <!-- if you dont set title in route then title is 'Page default' -->
  </title>
</head>
<body>

Upvotes: 0

Abel Wenning
Abel Wenning

Reputation: 651

1st) In your Express route:

app.get("/", function(req, res){
  res.locals.title = "Abel's Home Page";                    // THIS LINE IS KEY
  res.render("home.ejs");
});

2nd) In your views/home.ejs file:

<% include partials/header.ejs %>

3rd) In your views/partials/header.ejs file:

<!DOCTYPE html>
<html lang="en">
<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><%= title %></title>                               <!-- THIS LINE IS KEY -->
  <link rel="stylesheet" href="../style.css">
  <link rel="shortcut icon" href="../logo_sm.png" type="image/x-icon">
</head>
<body>

Upvotes: 7

Geert-Jan
Geert-Jan

Reputation: 18905

Each page that includes the partial is free to pass data to said partial through parameters. See here for an example.

Upvotes: 0

Related Questions