首頁  >  文章  >  web前端  >  使用 Pug 和 Express 提供動態 HTML

使用 Pug 和 Express 提供動態 HTML

PHPz
PHPz原創
2024-07-31 10:36:311051瀏覽

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 集成

要將 Pug 新增到您的 Express.js 專案中,只需使用您選擇的任何套件管理器安裝 Pug 即可。對於此範例,我正在使用 NPM:

npm i pug

這會將 Pug 加入到 package.json 檔案中的依賴項清單中。現在,您需要將視圖引擎設定為 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 中的視圖必須放置在專案根目錄中的特殊視圖目錄中。如果您還沒有建立視圖目錄,可以使用以下命令來建立:

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 會相對於視圖目錄定位 .pug 檔案。因此,如果您有一個位於views/layouts/main.pug 的Pug 文件,則在設定路線中的視圖時應稱為layouts/main。

app.get("/", (req, res) => {
  res.render("layouts/main");
});

接下來,局部變數是一個對象,其屬性定義了應傳遞到指定視圖進行插值的局部變數。提供回呼時,渲染操作產生的 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中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn