Node.js

[Node.js] Node.js Template Engine Nunjucks

건휘맨 2024. 11. 8. 15:48

Nunjucks를 프로젝트에 설치하려면, 다음 명령어로 패키지를 설치한다.

npm i nunjucks

 

 

설치 후, index.js 파일에서 nunjucks를 임포트하고, 템플릿 엔진을 사용하기 위한 설정을 추가

view engine을 설정하고, nunjucks.configure로 템플릿 파일 경로를 설정

앞서 정적 파일을 저장했던 public 과 다르게 화면을 구성하는 html 파일들을 views 라는 폴더에 저장해줄 것이기 때문에 경로는 views

이후에 watch, express 등의 설정을 추가한다.

import express from 'express';
import path from 'path';
import nunjucks from 'nunjucks';

const __dirname = path.resolve();

const app = express();

// view engine set
app.set('view engine main', 'html'); // 이렇게 작성하면 우리가 main.html 파일을 사용할 때 그냥 main 이라고 입력해도 뒤에 .html 이 붙게 된다.

// nunjucks
nunjucks.configure('views',{
    watch: true, // html 파일이 수정 될 경우에 그 값을 다시 반영 후 렌더링
    express: app
});

app.get('/', (req, res) => {
    res.sendFile(__dirname + '/public/main.html');
});


app.listen(3000, () => {
    console.log('Server is running');
});

 

이후, 프로젝트 폴더 내에 views 폴더를 생성하고, 공통 레이아웃인 base.html을 작성해보자

템플릿에서 변경되는 부분은 {% block content %}로 표시

항상 블록 단위를 사용할 때는 블록을 열어주고 닫아주어야 한다.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <!-- 공통 요소 -->
    <nav>
        <a href="">Logo</a>
        <a href="">글 작성</a>
    </nav>

    <!-- 바뀌는 요소 -->
    {% block content %}
    {% endblock %}

     <!-- 공통 요소 -->
     <footer>
        <p>Footer</p>
     </footer>
</body>
</html>

 

이제 write.html 파일을 작성하여 base.html 레이아웃을 상속받고, content 블록을 채워보자

{% extends 'base.html' %}

{% block content %}
<h1>글 작성 페이지입니다.</h1>
<form action="/write" method="post">
    <label for="title">제목</label>
    <input type="text" name="title" id="title">
    <br>
    <label for="contents">내용</label>
    <textarea name="contents" id="contents" cols="20" rows="5"></textarea>
    <br>
    <label for="date">날짜</label>
    <input type="date" name="date" id="date">
    <br>
    <!-- input submit -->
    <input type="submit" value="글 작성 완료">
</form>
{% endblock %}

 

마지막으로, index.js에서 write 페이지를 렌더링할 경로를 추가

경로를 입력할 때는 앞서 템플릿 엔진의 위치를 views 로 지정해줬기 때문에 write.html 만 입력해주면 된다.

import express from 'express';
import path from 'path';
import nunjucks from 'nunjucks';

const __dirname = path.resolve();

const app = express();

// view engine set
app.set('view engine main', 'html'); // 이렇게 작성하면 우리가 main.html 파일을 사용할 때 그냥 main 이라고 입력해도 뒤에 .html 이 붙게 된다.

// nunjucks
nunjucks.configure('views',{
    watch: true, // html 파일이 수정 될 경우에 그 값을 다시 반영 후 렌더링
    express: app
});

app.get('/', (req, res) => {
    res.sendFile(__dirname + '/public/main.html');
});

app.get('/write', (req, res) => {
    res.render('write.html')
})

app.listen(3000, () => {
    console.log('Server is running');
});

 

이렇게 설정하면 base.html을 레이아웃으로 사용하고, write.html에서 내용만 다르게 표시되는 페이지를 만들 수 있다!\