ホームページ  >  記事  >  ウェブフロントエンド  >  Pug と Express で動的 HTML を提供する

Pug と Express で動的 HTML を提供する

PHPz
PHPzオリジナル
2024-07-31 10:36:311046ブラウズ

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 のビューは、プロジェクトのルート ディレクトリ内の特別なビュー ディレクトリに配置する必要があります。ビュー ディレクトリを作成していない場合は、次のようにして作成できます:

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 ファイルをレンダリングしてクライアントに返す get リクエスト ハンドラーを定義します。

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");
});

次に、ローカル変数は、補間のために指定されたビューに渡される必要があるローカル変数を定義するプロパティを持つオブジェクトです。コールバックが提供される場合、レンダリング操作から得られる 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 メソッドに渡されたローカル オブジェクトの実際の値に置き換えられます。名前が定義されていない場合、エラーはスローされません。ここで実際に動作しています。

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 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。