MERN

⌘K
  1. Home
  2. Docs
  3. MERN
  4. template partials

template partials

Install Dependencies:

npm init -y
npm install express ejs

Project Structure:

- project
  - views
    - partials
      - header.ejs
    - layout.ejs
    - home.ejs
    - about.ejs
    - contact.ejs
  - public
    - styles
      - style.css
  - app.js
  - package.json

Files:

const express = require('express');
const app = express();
const port = 3000;

app.set('view engine', 'ejs');
app.use(express.static('public'));



app.get('/', (req, res) => {
  res.render('home', { title: 'Home' });
});

app.get('/about', (req, res) => {
  res.render('about', { title: 'About' });
});

app.get('/contact', (req, res) => {
  res.render('contact', { title: 'Contact' });
});

app.listen(port, () => {
  console.log(`Server is running at http://localhost:${port}`);
});

<!-- views/partials/header.ejs -->
<header>
  <h1>My Website</h1>
  <nav>
    <ul>
      <li><a href="/">Home</a></li>
      <li><a href="/about">About</a></li>
      <li><a href="/contact">Contact</a></li>
    </ul>
  </nav>
</header>

<!-- views/layout.ejs -->
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="/styles/style.css">
  <title><%= title %></title>
</head>
<body>
  <%- include('partials/header') %>

  <main>
    <!-- Content specific to each page goes here -->
    <%- body %>
  </main>
</body>
</html>

<!-- views/home.ejs -->
<%- include('layout', { title: 'Home' }) %>

<h2>Welcome to the Home Page</h2>
<p>This is the home page content.</p>

<!-- views/about.ejs -->
<%- include('layout', { title: 'About' }) %>

<h2>About Us</h2>
<p>This is the about page content.</p>

<!-- views/contact.ejs -->
<%- include('layout', { title: 'Contact' }) %>

<h2>Contact Information</h2>
<p>This is the contact page content.</p>

/* public/styles/style.css */
body {
  font-family: Arial, sans-serif;
  margin: 0;
  padding: 0;
}

header {
  background-color: #333;
  color: white;
  padding: 1em;
  text-align: center;
}

nav ul {
  list-style-type: none;
  padding: 0;
  margin: 0;
}

nav li {
  display: inline;
  margin-right: 20px;
}

nav a {
  color: white;
  text-decoration: none;
}

main {
  max-width: 800px;
  margin: 20px auto;
}

How can we help?