#5.1 Configuring Pug

jini.choi·2022년 7월 4일
0

유튜브 클론코딩

목록 보기
18/27

브라우저에 HTML을 리턴하는 두가지 옵션

  1. HTML의 문자열써서 보내는 방법(기본)

    • 컨트롤러안에 작성하기에는 너무 내용이 많다.
      export const see = (req, res) => res.send("<h1>See User</h1>");
  2. Pug(Template engine) (ㄱㅇㅇ😍)

    • 템플릿을 이용해서 뷰를 만드는것을 도와줌

    설치
    https://www.npmjs.com/package/pug
    gitHub
    https://github.com/pugjs/pug


Pug 사용법

  1. npm i pug 설치

  2. Express에게 pug를 뷰 엔진으로 사용한다고 설정

  • app.set("view engin", "pug");
  • express는 /views 폴더 안에 파일(view)을 찾음( view: 유저가 보는 대상 )
    • express가 view를 찾는 방법: process.cwd() + '/views'
    • 현재 작업 디렉토리에서 /views 라는 디렉토리를 찾음
    • 컨텍스트 안에서는 뷰나 템플릿이나 HTML이나 같은것
  1. '/src'디렉토리 안에 '/view'디렉토리 생성

  2. '/view'디렉토리에 'home.pug'파일 생성 후 pug 작성

doctype html
html(lang="ko")
    head
        title Wetube
    body
        h1 Welcom to Wetube
        footer &copy; 2022 Wetube
  1. 컨트롤러에서 유저에게 파일 전송
//view이름 작성 후 랜더링
// export const tranding = (req, res) => res.render("view"); 
export const tranding = (req, res) => res.render("home");
  • home.pug파일 그대로 유저에게 보내는것이 아님
    5.1. 우선 home.pug파일을 pug로 보냄
    5.2. pug가 home.pug 파일을 랜더링해서 평범한 html로 변환해줌

pug 작성 시

  • 모두 소문자로 작성
  • 속성이 있으면 괄호안에 작성 e.g.)script(type='text/javascript')
  • 모든 자식속성은 부모속성보다 안쪽탭에 있어야함(2칸띄우기 or Tab)

Pug 사용법 정리

  1. 이제 express는 우리가 템플릿 엔진으로써 pug를 쓴다는 것을 앎
    app.set("view engin", "pug");
  2. 우리는 express가 views라는 디렉토리에 있는 view를 본다는것도 앎
    process.cwd() + '/views'
  3. express가 view 디렉토리에서 pug파일을 찾도록 설정되어 있어서 우리는 따로 import할 필요없고 그저 res.render로 home.pug를 랜더링 하면됨

res.render(): http://expressjs.com/en/5x/api.html#res.render


에러

  • root폴더: \Users\jini.choi\Documents\wetube
  • 기본적으로 express는 cwd + /views에서 pug파일을 찾는다.
  • 현재 viwes폴더는 cwd/src/views에 있기때문에 에러난다.
  • root파일은 어디서 node.js를 부르고, 어디서 서버를 기동하는 파일의 위치에 따라 결정
    • package.json

에러고치기

  • 디폴트 값을 변경(기존: process.cwd() + '/views')
    app.set("views", process.cwd() + "/src/views");

app.set(name, value)

Assigns setting name to value. You may store any value that you want, but certain names can be used to configure the behavior of the server. These special names are listed in the app settings table.
Calling app.set('foo', true) for a Boolean property is the same as calling app.enable('foo'). Similarly, calling app.set('foo', false) for a Boolean property is the same as calling app.disable('foo').
Retrieve the value of a setting with app.get().

app.set('title', 'My Site')
app.get('title') // "My Site"
PropertTypeDescriptionDefault
viewsString or Array어플리케이션 views에 대한 디렉토리 또는 디렉토리 배열입니다. 배열인 경우 view는 배열에서 발생한 순서대로 조회됩니다.process.cwd() + '/views'
view engineString생략할 때 사용할 default engine 확장입니다.                NOTE: 하위 앱은 이 설정의 값을 상속합니다.N/A (undefined)

원본 문서 URL: http://expressjs.com/en/5x/api.html#app.set

profile
개발짜🏃‍♀️

0개의 댓글