Pug 및 Express를 사용하여 동적 HTML 제공

PHPz
풀어 주다: 2024-07-31 10:36:31
원래의
1045명이 탐색했습니다.

Serving Dynamic HTML With Pug And Express

단일 페이지 애플리케이션이 등장하기 전에는 개발자가 페이지를 클라이언트에 보내기 전에 서버 측에서 렌더링할 수 있었기 때문에 Pug와 같은 템플릿 언어가 매우 인기가 있었습니다. Express는 Node.js를 위한 가장 널리 사용되는 백엔드 애플리케이션 프레임워크입니다. 가볍고, 의견이 없으며, 사용이 최소화된 것을 자랑스럽게 생각합니다. 이 가이드에서는 Express.js 서버 애플리케이션에서 Pug를 사용하여 동적 HTML을 제공하는 방법을 배웁니다.

퍼그는 어떻게 작동하나요?

HTML은 때때로 작성하기 어려울 수 있습니다. 언어는 "구성 요소"와 같은 기능을 지원하지 않으므로 JavaScript와 같은 외부 도구를 사용하지 않으면 코드 중복이 발생할 수 있습니다.

Pug는 HTML 작성을 더 쉽게 해주는 템플릿 엔진입니다. Pug를 사용하면 코드를 분할하고 원하는 만큼 많은 위치에서 "구성 요소"를 재사용할 수 있습니다. 구문과 관련하여 Pug는 닫는 태그 대신 들여쓰기를 사용한다는 점에서 기존 HTML과 다릅니다. HTML에서는 다음과 같은 요소를 정의합니다.

<div class='hello'>This is something worth noting</div>
로그인 후 복사

그러나 Pug에서는 다음과 같은 요소를 정의합니다.

div(class='hello') This is something worth noting
로그인 후 복사

태그 이름은 왼쪽에 정의되어 있으며 해당 속성은 괄호 안에 표시됩니다. 태그는 옆의 공백으로 내용과 구분됩니다. Pug 트랜스파일러는 귀하의 코드를 브라우저가 인식하는 적절한 HTML 코드로 다시 트랜스파일합니다. 하위 요소는 들여쓰기로 정의됩니다. 즉, 기본 태그 안에 div를 포함하려면 다음과 같이 하면 됩니다.

main
div Hello from the children of planet Earth!
로그인 후 복사

Pug와 Express 통합

Express.js 프로젝트에 Pug를 추가하려면 원하는 패키지 관리자와 함께 Pug를 설치하기만 하면 됩니다. 이 예에서는 NPM을 사용하여 작업하고 있습니다.

npm i pug
로그인 후 복사

이렇게 하면 package.json 파일의 종속성 목록에 Pug가 추가됩니다. 이제 뷰 엔진을 pug로 설정해야 하므로 프로젝트 항목 파일(보통 main.js, app.js 또는 index.js)에서 express를 올바르게 가져오고 set 메소드를 사용하여 애플리케이션 설정을 구성합니다.

import express from 'express';
const app = express();

app.set('view engine', 'pug');
로그인 후 복사

뷰 엔진을 'pug'로 설정하면 Express에서 Pug를 템플릿 엔진으로 사용하도록 지시하는 것입니다. 따라서 응답 객체에서 render 메서드를 호출할 때 Express가 렌더링할 유효한 '뷰'를 전달해야 합니다. Express의 보기는 프로젝트 루트 디렉터리의 특수 보기 디렉터리에 배치되어야 합니다. views 디렉토리를 생성하지 않은 경우 다음을 사용하여 생성할 수 있습니다.

mkdir views
# Make sure you are in your project root 
로그인 후 복사

이제 모든 설정이 완료되었으므로 Pug에서 첫 번째 뷰를 작성해 보겠습니다.

Express 프로젝트의 기본 Pug 사용법

views/index.pug 파일을 생성하고 다음을 추가합니다.

html
  head
    title Welcome to my website
  body
    div Hello World
로그인 후 복사

이제 index.pug 파일이 준비되었으므로 이를 경로의 클라이언트에 제공해야 합니다. 프로젝트의 항목 파일로 이동하여 views/index.pug 파일을 렌더링하고 클라이언트에 반환하는 요청 가져오기 핸들러를 정의하세요.

app.get("/", (req, res) => {
  res.render("index.pug");
});
로그인 후 복사

localhost:를 열면 화면에 "Hello World" 메시지가 인쇄되는 것을 볼 수 있습니다. get 메소드의 콜백 함수에서 가장 간단한 형태의 res.render 사용법을 볼 수 있습니다. render 메서드의 구문은 다음과 같습니다.

res.render(view [, locals] [, callback]);
로그인 후 복사

먼저 렌더링하려는 .pug 파일의 경로인 뷰가 있습니다. Express는 views 디렉토리를 기준으로 .pug 파일을 찾습니다. 따라서 views/layouts/main.pug에 Pug 파일이 있는 경우 경로에서 보기를 설정할 때 이를layouts/main으로 참조해야 합니다.

app.get("/", (req, res) => {
  res.render("layouts/main");
});
로그인 후 복사

다음으로, locals는 보간을 위해 지정된 뷰에 전달되어야 하는 지역 변수를 정의하는 속성을 가진 개체입니다. 콜백이 제공되면 렌더링 작업의 결과 HTML이 클라이언트로 전송되지 않습니다. 대신 다음과 같이 콜백 함수의 매개변수를 통해 액세스할 수 있습니다.

app.get("/", (req, res) => {
  res.render("index.pug", {}, (err, html) => {
    console.log(html);
  });
});
로그인 후 복사

클라이언트가 '/'에 get 요청을 하면 응답이 전송되지 않습니다. 대신 html이 서버 콘솔에 기록됩니다. send 메소드를 사용하여 HTML을 클라이언트에 수동으로 보낼 수 있습니다:

res.send(html)
로그인 후 복사

동적 HTML 페이지 구축

이제 다음 단계로 나아갈 시간입니다. Pug를 사용하여 데이터를 보간하여 즉시 동적 콘텐츠를 만드는 방법을 알아봅니다. Pug에서 문자열 보간은 #{} 구문을 사용하여 수행됩니다. 컴파일 시 #{}은 실제 값으로 확인됩니다. 예시는 다음과 같습니다.

// greet.pug
html
  head
    title Welcome to my website
  body
    div Hello #{name}
로그인 후 복사

위 코드 블록에서 name은 render 메소드에 전달된 locals 객체의 실제 값으로 대체됩니다. 이름이 정의되지 않은 경우 오류가 발생하지 않습니다. 실제로 작동하는 모습입니다.

app.get('/greet', (req, res) => {
    const {name} = req.query;
    res.render('greet.pug', {name})
})
로그인 후 복사

클라이언트가 /greet?name=David를 누르면 다음 HTML이 반환됩니다

<html>
  <head>
    <title>Welcome to my website</title>
  </head>
  <body>
    <div>Hello David</div>
  </body>
</html>
로그인 후 복사

The string interpolation syntax (#{}), is escaped by Pug. This is useful in situations where the content comes from users. If you want Pug is render the string as is without escaping, you'll need to use the !{} syntax.

- var example = <strong>very risky</strong>
div !{example}
로그인 후 복사

Tags and Tag Intepolation in Pug

Pug provides a handy syntax for tag interpolation #[], which you can use like this:

  1. Basic Tag Interpolation: You can interpolate a tag directly within text.
p This is a #[strong very important] message.
로그인 후 복사

This will render as:

<p>This is a <strong>very important</strong> message.</p>
로그인 후 복사
  1. Interpolating with Variables: You can also interpolate tags with variables.
- var username = 'John' 
p Hello, #[strong #{username}]!
로그인 후 복사

You don't have to worry about self-closing tags, because Pug knows what tags are self closing. But if you really need to self-close a tag, you can append the / character to the end of the tag like this:

div/
로그인 후 복사

To save space, You can use the : shorthand instead of indentation to specify nested tags.

label: input(type='text' name='username')
로그인 후 복사

The code block above is just as valid as:

label
    input(type='text' name='username')
로그인 후 복사

Using JavaScript in Pug

In the last code block, notice the use of the var keyword from JavaScript to create a variable. Pug allows you to insert valid JavaScript code on any line that starts with an -. For example, you can create an array and iterate over it to render a list of items. Pug has its native syntax for this, but in this example, you can use JavaScript.

html
  head
    title Welcome to my website
  body
    div List of items 
    - var items = ['milk', 'peas', 'bread']
    - items.forEach((item)=>{
      li #{item}
    - })
로그인 후 복사

Study the previous example. Notice how Pug and JavaScript are combined. The forEach method is not part of the Pug API, it belongs to JavaScript. Likewise, the string interpolation symbol is not part of the #{} JavaScript API. The lines with valid JavaScript code are marked with the - symbol. On the second to last line, there is no - symbol, because that is Pug code.

Iteration and conditionals with Pug

For common things like conditionals and iteration, Pug provides its syntax that you can use instead of JavaScript. The most popular keyword for iteration in Pug is each. each must come in the form each VARIABLE_NAME of JS_EXPRESSION. Here's how you can use it:

each item in ['milk', 'peas', 'bread']
   li #{item}
로그인 후 복사

When dealing with objects, the expected format for each is each VALUE, KEY OF JS_EXPRESSION. For example:

each val, key in {1:'milk', 2:'peas', 3:'bread'}
  #{key} : #{val}
로그인 후 복사

You can use the if syntax to handle conditionals. Here's an example:

╴ var loggedIn = false

if !loggedIn
    p Sorry you cannot access this item because you're not logged in
로그인 후 복사

Conversely, Pug has an unless keyword that you can use like this:

unless loggedIn
    p Sorry you cannot access this item because you're not logged in
로그인 후 복사

Advanced Techniques with Pug

Pug offers many features beyond just string interpolation and conditionals. If you are working on a large website, you might need to use advanced features that Pug provides, such as layouts and partials.

Using Layout files for consistent page structure

Layout files allow you to define a common structure for your pages and extend it in other templates, ensuring consistency across your website. Here's an example of how you can use layout files.

//- views/layout.pug
html
  head
    title My Website Title
  body
    header
      h1 My Website
    block content
    footer
      p Footer content
로그인 후 복사

Notice the block keyword in the code block above. A block in a layout file acts as a placeholder. Each block must have a name. In this example, block is defined as content. Whenever you want to use your layout file, you use the extends syntax to tell Pug that a template should include a layout.

//- views/index.pug
extends layout

block content
  p Welcome to the homepage!
로그인 후 복사

In this example, index.pug extends the layout.pug template, which provides the page's base structure, including the header and footer. The block content line defines a block named content where the indented paragraph "Welcome to the homepage!" is inserted. When index.pug is rendered, the final HTML will look this this:

<html>
  <head>
    <title>My Website Title</title>
  </head>
  <body>
    <header>
      <h1>My Website</h1>
    </header>
    <p>Welcome to the homepage!</p>
    <footer>
      <p>Footer content</p>
    </footer>
  </body>
</html>
로그인 후 복사

Using Partials for Reusable Components

Partials are reusable pieces of templates that can be included in other templates, which helps to keep your code DRY (Don't Repeat Yourself). You can create partials in Pug with the include syntax.

//- views/partials/sidebar.pug
aside
  p This is the sidebar content.
로그인 후 복사

In sidebar.pug defines a partial template for a sidebar with an aside element containing a paragraph of text.

//- views/layout.pug
html
  head
    title My Website Title
  body
    include partials/sidebar
    block content
    footer
      p Footer content
로그인 후 복사

In layout.pug, a layout template is created with a basic HTML structure. It includes the header and sidebar partials using the include keyword, places a block content placeholder for dynamic content, and adds a footer with a paragraph of text. The final render should look something like this:

<html>
  <head>
    <title>My Website Title</title>
  </head>
  <body>
    <header></header>
    <aside>
      <p>This is the sidebar content.</p>
    </aside>
    <p>Welcome to the homepage!</p>
    <footer>
      <p>Footer content</p>
    </footer>
  </body>
</html>
로그인 후 복사

Tips for optimizing Pug templates

1. Use partials and layouts wherever you can: Using partials, layouts, and helpers in Pug enhances template organization and efficiency. Partials are reusable snippets that prevent code repetition, while layouts provide a consistent structure for pages by defining common elements and extending them in individual templates.

2. Minimize the use of inline JavaScript: When writing your templates, try to use inline JavaScript sparingly. Adding huge blocks of JavaScript to your code can create issues with debugging and maintainability.

One way to reduce inline JavaScript is through the use of helpers. Helpers, defined in the server-side code, allow dynamic content within templates. You can pass a helper function to a template using the locals method on the express app.

const express = require('express');
const app = express();

app.set('view engine', 'pug');

app.locals.formatDate = function(date) {
  return new Date(date).toLocaleDateString();
};

app.get('/', (req, res) => {
  res.render('index', { title: 'Home', currentDate: new Date() });
});

app.listen(3000, () => {
  console.log('Server is running on port 3000');
});
로그인 후 복사

With the formatDate helper function set, you can use it in your Pug template like this:

p Welcome to the homepage!
p Today's date is #{formatDate(currentDate)}
로그인 후 복사

Conclusion

In this guide, you learned how to serve dynamic HTML with Pug and Express. We covered basic Pug syntax, integrating Pug with Express, building dynamic pages, and advanced techniques like using layout files and partials.

Templating engines are very powerful especially when building a server-side web application. They are great for Search Engine optimization too because unlike single-page applications, the content is rendered on the server on each request.

위 내용은 Pug 및 Express를 사용하여 동적 HTML 제공의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!