본문 바로가기

Document 해석/PUG

NodeJS 템플릿 엔진 Pug(Jade) 시작하기

728x90
반응형
이 글은 NodeJS 템플릿 엔진인 Pug의 document를 해석한 글입니다.
영어 원문은 아래 바로가기를 클릭하거나 현재 글의 해석 아래 더보기를 클릭 시 확인하실 수 있습니다.
오타나 잘못된 해석은 댓글로 알려주시면 정정하겠습니다.

현재 페이지 본문 바로가기

설치

Pug는 npm을 통해 사용할 수 있습니다.

$ npm install pug

개요

Pug의 일반적인 렌더링 프로세스는 간단합니다.

pug.compile()은 데이터 객체("locals"라고 부르는)를 인수로 사용하는 자바스크립트 함수로, Pug 소스 코드를 컴파일합니다.

당신의 데이터를 사용하여 해당 함수를 호출하면, 데이터와 함께 렌더링된 HTML의 문자열이 반환됩니다.

 

컴파일된 함수를 재사용하거나 다른 데이터 세트를 호출할 수 있습니다.

더보기

pug.compile() will compile the Pug source code into a JavaScript function that takes a data object (called “locals”) as an argument.

Call that resultant function with your data, and voilà!, it will return a string of HTML rendered with your data.

 

The compiled function can be re-used, and called with different sets of data.

//- template.pug
p #{name}'s Pug source code!
const pug = require('pug');

// Compile the source code
const compiledFunction = pug.compileFile('template.pug');

// Render a set of data
console.log(compiledFunction({
  name: 'Timothy'
}));
// "<p>Timothy's Pug source code!</p>"

// Render another set of data
console.log(compiledFunction({
  name: 'Forbes'
}));
// "<p>Forbes's Pug source code!</p>"

Pug는 컴파일과 렌더링을 하나의 단계로 결합하는 pug.render() 함수 계열도 제공합니다.

하지만, 템플릿 함수는 렌더링을 호출할 때마다 다시 컴파일 되기 때문에 성능에 영향을 줄 수 있습니다.

대신 렌더링과 함께 캐시 옵션을 사용할 수 있습니다. 이 옵션을 사용하면 컴파일된 함수가 내부 캐시에 자동으로 저장됩니다.

더보기

Pug also provides the pug.render() family of functions that combine compiling and rendering into one step. However, the template function will be re-compiled every time render is called, which might impact performance. Alternatively, you can use the cache option with render, which will automatically store the compiled function into an internal cache.

const pug = require('pug');

// Compile template.pug, and render a set of data
console.log(pug.renderFile('template.pug', {
  name: 'Timothy'
}));
// "<p>Timothy's Pug source code!</p>"
728x90
반응형

'Document 해석 > PUG' 카테고리의 다른 글

Jade에서 Pug 2로 마이그레이션(이동) - 1  (0) 2021.01.18
Pug(Jade)의 method, properties  (0) 2021.01.16
Pug(Jade)의 옵션  (0) 2021.01.14
Pug(Jade)의 Express 통합  (0) 2021.01.12