728x90

사용자 요청을 처리하는 라우팅 함수를 컨트롤러(Controller), 데이터베이스에 데이터를 저장하거나 조회하는 함수를 Model, 사용자에게 결과를 보여주기 위해 만든 파일을 View 라고 한다.

 

먼저 프로젝트 안에 있는 index.js 파일을 열고 뷰 엔진을 ejs 로 저정한다.

그러면 이제부터는 ejs 로 만든 뷰 템플릿을 사용해 응답을 보낼 수 있다.

app 객체의 set() 메소드는 속성을 설정하는 역할을 한다.

 

ejs 모듈 설치

npm install ejs --save

 

 

index.js

// Package Imports
const express = require('express');
const path = require('path');
 
// App Definition
const app = express();
const port = 3000;
 
// 템플릿 엔진 설정
app.set('views', __dirname + '/views');
app.set('view engine''ejs');
app.engine('html', require('ejs').renderFile);
/***
 * 코드 실행 : <% %>
 * 결과 출력 : <%= %>
 */
 

 

 

nunjucks 모듈 설치

https://mozilla.github.io/nunjucks/getting-started.html

 

Nunjucks

Getting Started User-Defined Templates Warning nunjucks does not sandbox execution so it is not safe to run user-defined templates or inject user-defined content into template definitions. On the server, you can expose attack vectors for accessing sensitiv

mozilla.github.io

위 사이트를 참조해서 npm install nunjucks --save 로 모듈 설치한다.

 

파일을 분리하여 작성하는 방법으로 테스트한 사항을 적어둔다.

index.js 또는 app.js 파일

const express = require('express');
const path = require('path');
let nunjucks = require('nunjucks'); // templating framework
 
// App Definition
const app = express();
 
// Routes 파일 불러오기
const homeRoute = require('./routes/home');
const aboutRoute = require('./routes/about')
const adminRoute = require('./routes/admin');
 
const port = 3000;
 
dotenv.config({ path: './.env'})
 
// 템플릿 엔진 설정
app.set("view engine""html");
nunjucks.configure('views', {
    autoescape: true,
    express: app
});
 
 
app.use('/',homeRoute);
app.use('/about',aboutRoute)
app.use('/admin', adminRoute);
 
app.listen(port,() => {
    console.log('Start On', port);
});
 

 

routes 폴더 밑에 home.js 파일

const express = require('express');
const router = express.Router();
 
 
router.get('/', (req, res,next) => {
   //res.send('home 이후 url');
   res.render('index.html');
});
 
router.get('/login'function(req, res) {
   // Render login template
   res.render('login.html');
});
 
module.exports = router;

여기서 주의할 사항은 res.render('/index.html'); 이라고 하면 절대 안된다.

router.get('/' function(req, res, next){}) 에서 경로 / 가 이미 지정되었기 때문이다.

 

 

routes 폴더 밑에 admin.js 파일

const express = require('express');
const nunjucks = require('nunjucks');
const logger = require('morgan'); // 로그 미들웨어 npm install morgan
// 로그 미들웨어 winston 은 파일로 남기기, DB에 저장, email, sms, 알림 메시지 사용 npm install winston
const bodyParser = require('body-parser');
const router = express.Router();
// 라우터 수준의 미들웨어
 
router.get('/', (req, res) => {
   // res.send('admin 이후 url');
   res.render('admin/index.html');
});
 
router.get('/products', ( _ , res) => {
   res.render( 'admin/products.html' ,
       { message : "hello" } // message 란 변수를 템플릿으로 내보낸다.
   );
});
 
 
module.exports = router;
 

 

 

 

 

views 폴더 내 index.html

파일의 변수를 인식하는 처리 그리고 Layout을 분리하는 구조까지는 처리하지 않았다.

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Bootstrap Example</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css">
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.slim.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>
<nav class="navbar navbar-expand-sm bg-light navbar-light">
    <ul class="navbar-nav">
        <li class="nav-item"><class="nav-link" href="/">Home</a></li>
        <li class="nav-item"><class="nav-link" href="/login">Login</a></li>
        <li class="nav-item"><class="nav-link" href="/register">Register</a></li>
        <li class="nav-item"><class="nav-link" href="/admin">Admin</a></li>
    </ul>
</nav>
 
<div class="container">
    <h1>Welcome to My Homepage</h1>
    <h2>Basic Table</h2>
    <p>The .table class adds basic styling (light padding and horizontal dividers) to a table:</p>
    <table class="table">
        <thead>
        <tr>
            <th>Firstname</th>
            <th>Lastname</th>
            <th>Email</th>
        </tr>
        </thead>
        <tbody>
        <tr>
            <td>John</td>
            <td>Doe</td>
            <td>john@example.com</td>
        </tr>
        <tr>
            <td>Mary</td>
            <td>Moe</td>
            <td>mary@example.com</td>
        </tr>
        <tr>
            <td>July</td>
            <td>Dooley</td>
            <td>july@example.com</td>
        </tr>
        </tbody>
    </table>
</div>
 
</body>
</html>
 

 

위와 같은 구조로 동작된다는 걸 설명하기 위해서 테스트하고 적어둔 것이다.

 

views 폴더 하단에 layout 폴더를 추가하고 html 파일을 분리구조로 만드는 방법은 다음 게시글에 적어둘 것이다.

여기까지는 nunjucks 모듈을 설치하고 view 엔진으로 nunjucks 를 사용하는 간단 방법을 알아봤다.

블로그 이미지

Link2Me

,