Node.js - template engine(pug, nunjucks)

ryan·2022년 5월 17일
0

학습자료 : 인프런 Node.js 교과서

템플릿 엔진

  • Template engine?

    • 서버에서 클라이언트로 보낼 html의 형태를 미리 템플릿으로 저장.
    • 동작 시에 미리 작성된 템플릿에 데이터를 넣어 완성된 html 생성 템플릿 엔진은 템플릿 작성 문법과 작성된 템플릿을 html로 변환하는 기능을 제공.
  • HTML의 정적인 단점을 개선

  • 반복문, 조건문, 변수 등을 사용할 수 있음

  • 동적인 페이지 작성 가능

Pug

  • ruby와 비슷해 코드 양이 많이 줄어듦
  • 익스프레스에 app.set으로 퍼그 연결
  • 들여쓰기 표현식을 사용해 가독성이 좋고 개발 생산성이 높음 html을 잘 모르더라도 문법적 실수를 줄일 수 있음

pug 선언

const pug = require('pug')
app.set('views', //템플릿이 저장되는 디렉토리가 어딘지 지정
    path.join(__dirname,'views'))
app.set('view engin',pug); //퍼그라는 템플릿을 사용할 것이라고 선언

pug 표현식

#login-button  >> <div id="login-button"></div>
.post-image    >> <div class="post-image"></div>
span#highlight >> <span id="highlight"></span>
button(type="submit") 전송 >> <button type="submit">전송</button>

script. 
    const message = 'Pug';
    alert(message);
===
<script>
    const message='Pug' 
    alert(message);
</script>

pug 변수

  • res.render에서 두 번째 인수 객체에 Pug 변수를 넣음
router.get('/',function(req,res,next)=>{
    res.render('index',{title:'Express'}); // title이란 변수에 express 할당
});
  • res.locals 객체에 넣는 것도 가능(미들웨어간 공유됨)
    router.get('/',function(req,res,next){
        res.locals.title='Express'; // title이란 변수에 express 할당
        res.render('index');
    })
  • = #{}으로 변수 렌더링 가능(= 뒤에는 자바스크립트 문법 사용 가능)
h1 = title 
p Welcome to #{title}
button(class=title,type='submit') 전송
input(placeholder=title+'연습')

pug 파일 내 변수

  • -뒤에 자바스크립트 사용
- const node = 'node'
- const js = 'javascript'
p #{node}와 #{js} >> <p>node와 javascript</p>

pug 반복문

  • for in / each in으로 반복문 사용 가능 (값과 인덱스 가져올 수 있음)
    ul
  each fruit in ['사과','배','복숭아']
      li=fruit

pug 조건문

  • if else 문 case when 문 사용 가능
if isLoggedIn 
    div 로그인 되었습니다 
else
    div 로그인이 필요합니다.

case fruit
    when 'apple'
        p 사과입니다.
    when 'banana'
        p 바나나입니다 
    default 
        p 과일이 아닙니다.

pug inlcude

  • 퍼그 파일에 다른 퍼그 파일을 넣을 수 있음
  • 자주 반복되는 구문을 미리 작성해두고 include하여 사용할 수 있음
    ---header.pug
    header
    a(href='/') Home
    a(href='/about') About
    ---footer.pug
    footer
    div 푸터입니다
    ---main.pug
    include header
    main
    h1 메인
    p 문장
    include footer

pug extends와 block

  • 공통되는 레이아웃을 작성한 뒤 변경되는 부분을 block으로 선언하면 block를 호출해서 내용을 수정할 수 있음
  • layout을 extends하면 block 부분에 작성한 HTML 태그가 포함됨
  • 반복되는 웹사이트의 틀을 작성해두고 extends하며 개발하면 매우 편리
---layout.pug---
html
    head
        title=title
    body
        block content
---main.pug---
extends layout
block content
    h1 Main Page

mixin

  • 템플릿을 함수처럼 사용할 수 있게 선언할 수 있음
  • include는 값을 지정할 없지만 mixin은 파라미터를 지정하여 값을 넘겨받아 템플릿에 사용할 수 있음
---listImem.pug---
mixin listItem(title,name)
    tr
        td title 
        td name
--- main.pug---
include listItem
table
    tbody
        listItem('제목','이름')

nunjucks

  • nunjucks를 사용하고 싶다면 view engine을 html로 교체
const nunjucks = require('nunjucks'); 
nunjucks.configure('views', { express: app, watch: true, }); 

nunjucks 변수 {{변수}}

<h1>{{title}}</h1>
<p>welcome to {{title}}</p>
<button class="{{title}}" type="submit">전송</button>

내부 변수 선언 {%set 자바스크립트 구문}

{% set node ='Node.js'%} 
{% set js ='javascript'%}
<p>{{node}}와{{js}}</p> >> <p>Node.js와 javascript</p>

이스케이프

<p>{{'<strong>이스케이프</strong>'}}</p>
<p>{{'<strong>이스케이프 안함</strong>'|safe}}</p>

반복문

  • {% %} 내부에 for in 작성
  • index는 loop 키워드
<ul>
  {% set fruits =['사과','배','오렌지'] %} {% for item in fruits %}
  <li>{{item}}</li>
  {% endfor %}
</ul>

<ul>
  {% set fruits =['사과','배','오렌지'] %} {% for item in fruits %}
  <li>{{loop.index}}번째 {{item}}</li>
  {% endfor %}
</ul>

조건문

  • {% if %} 으로 작성
{% if isLoggedIn %}
<div>로그인 되었습니다.</div>
{% else %}
<div>로그인이 필요합니다.</div>
{% endif %} 

{% if fruit ==='apple' %}
<div>사과입니다.</div>
{% elif ==='바나나' %}
<div>바나나입니다.</div>
{% else %}
<p>과일이 아닙니다.</p>
{% endif %}

include

  • 다른 파일 불러올 수 있으며, include에 파일 경로 넣을 수 있다.
<!-- header.html -->
<header>
  <a href="/">home</a>
  <a href="/about">about</a>
</header>
<!-- footer.html -->
<footer>
  <div>푸터입니다.</div>
</footer>
<!-- main.html -->
{% include "header.html" %}
<main>
  <h1>메인</h1>
  <p>문장</p>
</main>
{% include "footer.html" %}

extends block

<!-- layout.html -->
<html>
  <header>
    <title>{{title}}</title>
    <link rel="stylesheet" href="" />
  </header>
  <body>
    <header>{% block content %} {% endblock %}</header>
    <footer>{% block script %} {% endblock %}</footer>
  </body>
</html>
<!-- body.html -->
{% extends 'layout.html' %} \
<!--  -->
{% block content %}
<main>
  <p>내용</p>
</main>
{% endblock %} {% block script %}
<script src="/main.js"></script>
{% endblock %}
profile
프론트엔드 개발자

0개의 댓글