Node.js 동적 콘텐츠 출력

이건선·2023년 1월 21일
0

Node.js

목록 보기
6/32

shop.js


// /routes/shop.js
const path = require('path');

const express = require('express');

const rootDir = require('../util/path');
const adminData = require('./admin');

const router = express.Router();

router.get('/', (req, res, next) => {
  const products = adminData.products;
  res.render('shop', {
    prods: products,
    pageTitle: 'Shop',
    path: '/',
  });
});

module.exports = router;

🧐 ejs


router.get('/', (req, res, next) => {
  const products = adminData.products;
  res.render('shop', {
    prods: products,
    pageTitle: 'Shop',
    path: '/',
  });

객체에 있는 모든 필드는 Shop.ejs템플릿에 전달되고 템플릿 내에서는 이것을 사용 할 수 있게된다.


🧐 include

// /views/includes/head.ejs
// 재사용할 부분을 떼어내고 다른 파일에 저장한다.

<!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><%= pageTitle %></title>
    <link rel="stylesheet" href="/css/main.css">

각각 다른 파일에 코드를 분리하고

// /views/404.ejs

<%- include('includes/head.ejs') %>
</head>
<body>
    <header class="main-header">
        <nav class="main-header__nav">
            <ul class="main-header__item-list">
                <li class="main-header__item"><a class="active" href="/">Shop</a></li>
                <li class="main-header__item"><a href="/admin/add-product">Add Product</a></li>
            </ul>
        </nav>
    </header>
    <h1>Page Not Found!</h1>
</body>

</html>

떼어낸 부분에 <%- include('includes/head.ejs') %> 를 붙인다. "=" 이 아니라 "-" 사용에 주의하자. include를 사용해서 header태그와 /body /html 부분도 재사용이 가능하게 만들 수 있다.
// /views/404.ejs
<%- include('includes/head.ejs') %>
    </head>

    <body>
        <%- include('includes/navigation.ejs') %>
            <h1>Page Not Found!</h1>
<%- include('includes/end.ejs') %>

🧐 header부분의 active가 이상동작 한다면

<ul class="main-header__item-list">
            <li class="main-header__item">
            <a class="<%= path === '/' ? 'active' : ''%>" href="/">
            Shop</a></li>
            <li class="main-header__item">
            <a class="<%= path === '/admin/add-product' ? 'active' : ''%>" href="/admin/add-product">
            Add Product</a></li>
        </ul>
           

class에 삼항 연산자를 넣어서 해결해보자

profile
멋지게 기록하자

0개의 댓글