Heim  >  Artikel  >  Web-Frontend  >  Dynamisches HTML mit Pug und Express bereitstellen

Dynamisches HTML mit Pug und Express bereitstellen

PHPz
PHPzOriginal
2024-07-31 10:36:311046Durchsuche

Serving Dynamic HTML With Pug And Express

Bevor Single-Page-Anwendungen aufkamen, waren Vorlagensprachen wie Pug äußerst beliebt, da sie es Entwicklern ermöglichten, eine Seite auf der Serverseite zu rendern, bevor sie an den Client gesendet wurden. Express ist das beliebteste Backend-Anwendungsframework für Node.js. Es ist stolz darauf, leicht, uneinsichtig und minimal in der Anwendung zu sein. In dieser Anleitung erfahren Sie, wie Sie dynamisches HTML mit Pug aus einer Express.js-Serveranwendung bereitstellen.

Wie funktioniert Mops?

HTML kann manchmal umständlich zu schreiben sein. Die Sprache unterstützt keine Funktionen wie „Komponenten“, was zu Codeduplizierung führen kann, es sei denn, Sie verlassen sich auf externe Tools wie JavaScript.

Pug ist eine Template-Engine, die das Schreiben von HTML erleichtert. Mit Pug können Sie Ihren Code aufteilen und „Komponenten“ an beliebig vielen Stellen wiederverwenden. Hinsichtlich der Syntax unterscheidet sich Pug von herkömmlichem HTML, da es Einrückungen statt schließender Tags verwendet. In HTML definieren Sie ein Element wie folgt:

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

In Pug definieren Sie jedoch ein Element wie folgt:

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

Der Tag-Name wird auf der linken Seite definiert, mit seinen Attributen in Klammern. Das Tag wird durch das Leerzeichen daneben von seinem Inhalt getrennt. Der Pug-Transpiler transpiliert Ihren Code zurück in den richtigen HTML-Code, der vom Browser erkannt wird. Untergeordnete Elemente werden durch Einrückung definiert. Das heißt, wenn Sie ein div innerhalb eines Haupt-Tags haben möchten, würden Sie so etwas tun:

main
div Hello from the children of planet Earth!

Pug mit Express integrieren

Um Pug zu Ihrem Express.js-Projekt hinzuzufügen, installieren Sie Pug einfach mit einem beliebigen Paketmanager Ihrer Wahl. In diesem Beispiel arbeite ich mit NPM:

npm i pug

Dadurch wird Pug zu Ihrer Abhängigkeitsliste in Ihrer package.json-Datei hinzugefügt. Jetzt müssen Sie Ihre Ansichts-Engine auf pug einstellen, also in der Eintragsdatei Ihres Projekts (normalerweise main.js, app.js oder index.js) Express ordnungsgemäß importieren und die Anwendungseinstellungen mit der Set-Methode konfigurieren.

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

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

Indem Sie die Ansichts-Engine auf „pug“ setzen, weisen Sie Express an, Pug als Template-Engine zu verwenden. Wenn Sie also die Render-Methode für das Antwortobjekt aufrufen, müssen Sie eine gültige „Ansicht“ übergeben, damit Express sie rendern kann. Ansichten in Express müssen in einem speziellen Ansichtsverzeichnis im Stammverzeichnis des Projekts abgelegt werden. Wenn Sie kein Ansichtenverzeichnis erstellt haben, können Sie dies wie folgt tun:

mkdir views
# Make sure you are in your project root 

Da Sie nun alles vorbereitet haben, beginnen wir mit dem Schreiben unserer ersten Ansicht in Pug.

Grundlegende Verwendung von Mops in einem Express-Projekt

Erstellen Sie eine Datei „views/index.pug“ und fügen Sie Folgendes hinzu:

html
  head
    title Welcome to my website
  body
    div Hello World

Da Ihre index.pug-Datei nun fertig ist, müssen Sie sie dem Client auf einer Route bereitstellen. Gehen Sie zur Eintragsdatei Ihres Projekts und definieren Sie einen Get-Request-Handler, der die Datei „views/index.pug“ rendert und an den Client zurückgibt.

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

Wenn Sie localhost: öffnen, sollte die Meldung „Hallo Welt“ auf dem Bildschirm angezeigt werden. In der Rückruffunktion der get-Methode sehen Sie die Verwendung von res.render in seiner einfachsten Form. Die Syntax für die Render-Methode ist unten dargestellt:

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

Zuerst haben wir eine Ansicht, bei der es sich einfach um den Pfad der .pug-Datei handelt, die Sie rendern möchten. Denken Sie daran, dass Express die .pug-Dateien relativ zum Verzeichnis „views“ sucht. Wenn Sie also eine Pug-Datei unter „views/layouts/main.pug“ haben, sollten Sie diese beim Festlegen der Ansicht in Ihrer Route als „layouts/main“ bezeichnen.

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

Als nächstes handelt es sich bei „Locals“ um ein Objekt mit Eigenschaften, die lokale Variablen definieren, die zur Interpolation an die angegebene Ansicht übergeben werden sollen. Wenn ein Rückruf bereitgestellt wird, wird der resultierende HTML-Code des Rendervorgangs nicht an den Client gesendet. Stattdessen können Sie über einen Parameter in der Callback-Funktion darauf zugreifen, etwa so:

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

Wenn der Client eine Get-Anfrage an „/“ stellt, wird keine Antwort gesendet. Stattdessen wird HTML an der Serverkonsole protokolliert. Sie können den HTML-Code manuell mit der Sendemethode:
an den Client senden

res.send(html)

Erstellen dynamischer HTML-Seiten

Jetzt ist es an der Zeit, die Dinge auf die nächste Stufe zu bringen. Sie erfahren, wie Sie Daten mit Pug interpolieren, um im Handumdrehen dynamische Inhalte zu erstellen. In Pug erfolgt die String-Interpolation mit der Syntax #{}. Zur Kompilierungszeit wird #{} in seinen tatsächlichen Wert aufgelöst. Hier ist ein Beispiel.

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

Im obigen Codeblock wird der Name durch den tatsächlichen Wert des lokalen Objekts ersetzt, das an die Render-Methode übergeben wird. Wenn der Name nicht definiert ist, wird kein Fehler ausgegeben. Hier ist es in Aktion.

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

Wenn der Client auf /greet?name=David klickt, wird der folgende HTML-Code zurückgegeben

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

Das obige ist der detaillierte Inhalt vonDynamisches HTML mit Pug und Express bereitstellen. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn