본문 바로가기

BackEnd/Node.js

[Backend]Express_pug

Pug는 Express에서 제공하는 템플릿 엔진이다.


View단에 HTML코드를 작성할 때 사용된다.




npm으로 pug를 설치한 후에 사용하면 되는데

pug는 express로 동작하는 것이기 때문에


const globalRouter = express.Router();

globalRouter.get(routes.home,home)


다음과 같이 import없이


Router에 달아두기만 하면 실행된다.



home.pug

1. extends layouts/main

block content
p Home


layouts/main.pug

doctype html
html
head
<link rel="stylesheet"
href="https://use.fontawesome.com/releases/v5.6.3/css/all.css"
integrity="sha384-UHRtZLI+pbxtHCWp1t77Bi1L4ZtiqrqD80Kn4Z8NTSRyMA2Fd33n5dQ8lWUE00s/"
crossorigin="anonymous">
title 3. #{siteName}
body
2. include ../partials/header
main
block content
include ../partials/footer


partials/header.pug

header.header
div.header_column
a(href=route.home)
i.fab.fa-youtube
div.header_column
ul
li
a(href=route.join) Join
li
a(href=route.login) Log in


python처럼 들여쓰기를 함.


1. extends layouts/main은

말 그대로 main.pug로 해당 파일을 연장한다는 뜻인데


home의 위치를 main에 지정해주고 home은 따로 관리하는 식으로 사용되고 있다.


2. inculde ../partials/header.pug는

부분적인 태그를 불러오기 위해 사용되어졌다.


3. 자바스크립트를 pug에서 사용하기 위해선 #{ } 에 입력하면 된다.


그렇다면 siteName이라는 변수는 무엇일까?


아마 어떤 데이터들은 대부분 지역변수로써 전역변수로 바꾸어 파일을 불러올 때 사용되어야 할 텐데( React-Redux에서 사용되듯이)


이도 전역변수화된 변수이다.


app.js

import { localsMiddleware} from "./middlewares"
app.use(localsMiddleware)


app에 새로운 미들웨어를 추가 했는데 이는 커스텀된 미들웨어이다.


import routes from "./routes"

export const localsMiddleware = (req, res, next) => {
res.locals.siteName = "Movie";
res.locals.route = routes;
next();
};


express의 미들웨어는 지역변수를 전역변수로 만들어주는 속성이 존재하는데


res.locals.변수 이다.

이를 통해서 다음과 같은 변수를 추가 했다.


이때 route는


//Global
const HOME = "/";
const JOIN = "/join";
const LOGIN = "/login";
const LOGOUT = "/logout";
const SEARCH = "search";

.

.

.

const routes = {
home : HOME,
join : JOIN,
login : LOGIN,
logout : LOGOUT,
search : SEARCH,
users : USERS,
userDetail : USER_DETAIL,
editProfile : EDIT_PROFILE,
changePassword : CHANGE_PASSWORD,
videos : VIDEOS,
upload : UPLOAD,
videoDetail : VIDEO_DETAIL,
editVideo : EDIT_VIDEO,
deleteVideo : DELETE_VIDEO
};

export default routes;


URL을 담아둔 객체

'BackEnd > Node.js' 카테고리의 다른 글

[Express]Pug mixins  (0) 2019.01.25
[Express] Form get  (0) 2019.01.25
[Express]Route  (0) 2019.01.25
[Express]요청 응답 미들웨어  (0) 2019.01.25
[BackEnd]Express start  (0) 2019.01.24