Rumah  >  Artikel  >  hujung hadapan web  >  Menyediakan HTML Dinamik Dengan Pug Dan Express

Menyediakan HTML Dinamik Dengan Pug Dan Express

PHPz
PHPzasal
2024-07-31 10:36:311051semak imbas

Serving Dynamic HTML With Pug And Express

Sebelum Aplikasi Satu Halaman menjadi satu perkara, bahasa templat seperti Pug sangat popular kerana ia membenarkan pembangun memaparkan halaman di bahagian pelayan sebelum menghantarnya kepada pelanggan. Express ialah rangka kerja aplikasi bahagian belakang yang paling popular untuk Node.js. Ia berbangga kerana ringan, tidak mempunyai pendapat, dan minimum untuk digunakan. Dalam panduan ini, anda akan belajar cara menyajikan HTML dinamik dengan Pug daripada aplikasi pelayan Express.js.

Bagaimanakah Pug berfungsi?

HTML kadangkala menyusahkan untuk ditulis. Bahasa ini tidak mempunyai sokongan untuk ciri seperti "komponen", yang boleh membawa kepada pertindihan kod melainkan anda bergantung pada alat luaran seperti JavaScript.

Pug ialah enjin templat yang memudahkan untuk menulis HTML. Dengan Pug, anda boleh membahagikan kod anda dan menggunakan semula "komponen" di seberapa banyak tempat yang anda mahu. Mengenai sintaks, Pug berbeza daripada HTML tradisional kerana ia menggunakan lekukan dan bukannya teg penutup. Dalam HTML, anda mentakrifkan elemen seperti ini:

<div class='hello'>This is something worth noting</div>

Walau bagaimanapun, dalam Pug, anda mentakrifkan elemen seperti ini:

div(class='hello') This is something worth noting

Nama teg ditakrifkan di sebelah kiri, dengan atributnya dalam kurungan. Teg dipisahkan daripada kandungannya dengan ruang di sebelahnya. Transpiler Pug akan mentranspile kod anda kembali kepada kod HTML yang betul yang diiktiraf oleh penyemak imbas. Elemen kanak-kanak ditakrifkan melalui lekukan. Ini bermakna jika anda ingin mempunyai div dalam teg utama, anda akan melakukan sesuatu seperti ini:

main
div Hello from the children of planet Earth!

Mengintegrasikan Pug dengan Express

Untuk menambahkan Pug pada projek Express.js anda, cuma pasang Pug dengan mana-mana pengurus pakej pilihan anda. Untuk contoh ini, saya bekerja dengan NPM:

npm i pug

Ini akan menambahkan Pug pada senarai kebergantungan anda dalam fail package.json anda. Sekarang, anda perlu menetapkan enjin paparan anda kepada pug, jadi dalam fail kemasukan projek anda (biasanya main.js, app.js atau index.js ), import ekspres dengan betul dan konfigurasikan tetapan aplikasi dengan kaedah yang ditetapkan.

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

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

Dengan menetapkan enjin paparan kepada 'pug', anda memberitahu Express untuk menggunakan Pug sebagai enjin templatnya. Jadi, apabila anda memanggil kaedah render pada objek respons, anda mesti lulus 'view' yang sah untuk Express untuk membuat. Paparan dalam Ekspres mesti diletakkan dalam direktori pandangan khas, dalam direktori akar projek. Jika anda belum mencipta direktori pandangan, anda boleh berbuat demikian dengan yang berikut:

mkdir views
# Make sure you are in your project root 

Sekarang, anda telah menyediakan sesuatu, mari teruskan menulis paparan pertama kami dalam Pug.

Penggunaan Asas Pug dalam Projek Ekspres

Buat fail views/index.pug, dan tambahkan yang berikut padanya:

html
  head
    title Welcome to my website
  body
    div Hello World

Memandangkan fail index.pug anda sudah sedia, anda perlu menyampaikannya kepada pelanggan pada laluan. Pergi ke fail kemasukan projek anda dan tentukan pengendali permintaan get yang akan memaparkan dan mengembalikan fail views/index.pug kepada klien.

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

Apabila anda membuka localhost:, anda sepatutnya melihat mesej "Hello World" dicetak pada skrin. Dalam fungsi panggil balik kaedah get, anda akan melihat penggunaan res.render dalam bentuk yang paling mudah. Sintaks untuk kaedah pemaparan ditunjukkan di bawah:

res.render(view [, locals] [, callback]);

Pertama, kami mempunyai paparan, iaitu laluan fail .pug yang ingin anda berikan. Ingat bahawa Express mencari fail .pug berbanding dengan direktori pandangan. Jadi, jika anda mempunyai fail Pug yang terletak di views/layouts/main.pug, anda harus merujuknya sebagai susun atur/utama apabila menetapkan paparan dalam laluan anda.

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

Seterusnya, tempatan ialah objek dengan sifat yang mentakrifkan pembolehubah setempat yang harus dihantar ke paparan yang ditentukan untuk interpolasi. Apabila panggilan balik disediakan, HTML yang terhasil daripada operasi render tidak dihantar kepada klien. Sebaliknya, anda boleh mengaksesnya melalui parameter dalam fungsi panggil balik, seperti ini:

app.get("/", (req, res) => {
  res.render("index.pug", {}, (err, html) => {
    console.log(html);
  });
});

Apabila pelanggan membuat permintaan dapatkan kepada '/', jawapan tidak dihantar. Sebaliknya, html dilog ke konsol pelayan. Anda boleh menghantar HTML secara manual kepada klien dengan kaedah hantar:

res.send(html)

Membina Halaman HTML Dinamik

Kini tiba masanya untuk membawa perkara ke peringkat seterusnya. Anda akan belajar cara menginterpolasi data dengan Pug untuk mencipta kandungan dinamik dengan cepat. Dalam Pug, interpolasi rentetan dilakukan dengan sintaks #{}. Pada masa penyusunan, #{} diselesaikan kepada nilai sebenar. Ini contohnya.

// greet.pug
html
  head
    title Welcome to my website
  body
    div Hello #{name}

Dalam blok kod di atas, nama akan digantikan dengan nilai sebenar daripada objek tempatan yang dihantar ke kaedah pemaparan. Jika nama tidak ditentukan, tiada ralat dilemparkan. Ini sedang beraksi.

app.get('/greet', (req, res) => {
    const {name} = req.query;
    res.render('greet.pug', {name})
})

Apabila pelanggan memukul /greet?name=David, HTML berikut akan dikembalikan

<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.

Atas ialah kandungan terperinci Menyediakan HTML Dinamik Dengan Pug Dan Express. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

Kenyataan:
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn