”工欲善其事,必先利其器。“—孔子《论语.录灵公》
首页 > 编程 > 使用 Pug 和 Express 提供动态 HTML

使用 Pug 和 Express 提供动态 HTML

发布于2024-08-19
浏览:734

Serving Dynamic HTML With Pug And Express

Before Single Page Applications became a thing, templating languages like Pug were super popular because they allowed developers to render a page on the server side before sending it over to the client. Express is the most popular backend application framework for Node.js. It prides itself on being lightweight, unopinionated, and minimal to use. In this guide, you will learn how to serve dynamic HTML with Pug from an Express.js server application.

How does Pug work?

HTML can be cumbersome to write sometimes. The language has no support for features like "components", which can lead to code duplication unless you rely on external tools like JavaScript.

Pug is a templating engine that makes it easier to write HTML. With Pug, you can split your code and reuse "components" in as many places as you'd like. Regarding syntax, Pug differs from traditional HTML as it uses indentation instead of closing tags. In HTML, you define an element like this:

This is something worth noting

In Pug, however, you define an element like this:

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

The tag name is defined on the left, with its attributes in brackets. The tag is separated from its contents by the space next to it. The Pug transpiler will transpile your code back to the proper HTML code recognized by the browser. Child elements are defined by indentation. This means if you wanted to have a div inside a main tag, you'd do something like this:

main
div Hello from the children of planet Earth!

Integrating Pug with Express

To add Pug to your Express.js project, simply install Pug with any package manager of your choice. For this example, I'm working with NPM:

npm i pug

This will add Pug to your list of dependencies in your package.json file. Now, you'll need to set your view engine to pug, so in your project's entry file (usually main.js, app.js, or index.js ), import express properly and configure the application settings with the set method.

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

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

By setting view engine to 'pug', you're telling Express to use Pug as its templating engine. So, when you call the render method on the response object, you must pass a valid 'view' for Express to render. Views in Express must be placed in a special views directory, in the project's root directory. If you haven't created a views directory, you can do so with the following:

mkdir views
# Make sure you are in your project root 

Now, that you've got things set up, let's proceed to writing our first view in Pug.

Basic Pug Usage in an Express Project

Create a views/index.pug file, and add the following to it:

html
  head
    title Welcome to my website
  body
    div Hello World

Now that your index.pug file is ready, you'll need to serve it to the client on a route. Go to your project's entry file and define a get request handler that will render and return the views/index.pug file to the client.

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

When you open localhost:, you should see the "Hello World" message printed on the screen. In the callback function of the get method, you'll see the usage of res.render in its simplest form. The syntax for the render method is shown below:

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

First, we have view, which is simply the path of the .pug file you want to render. Remember that Express locates the .pug files relative to the views directory. So, if you have a Pug file located at views/layouts/main.pug, you should refer to it as layouts/main when setting the view in your route.

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

Next, the locals is an object with properties that define local variables that should be passed into the specified view for interpolation. When callback is provided, the resulting HTML from the render operation is not sent to the client. Instead, you can access it via a parameter in the callback function, like this:

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

When the client makes a get request to '/', a response is not sent. Instead, html is logged to the server console. You can manually send the HTML to the client with the send method:

res.send(html)

Building Dynamic HTML Pages

Now it's time to take things to the next level. You'll learn how to interpolate data with Pug to create dynamic content on the fly. In Pug, string interpolation is done with the syntax #{}. At compilation time, #{} is resolved to its actual value. Here's an example.

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

In the code block above, name will be replaced the actual value from the locals object passed into the render method. If name is undefined, no error is thrown. Here it is in action.

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

When the client hits /greet?name=David, the following HTML will be returned

  
    Welcome to my website
Hello David

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 = very risky
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:

This is a very important message.

  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:

  
    My Website Title

My Website

Welcome to the homepage!

Footer content

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:

  
    My Website Title

Welcome to the homepage!

Footer content

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.

版本声明 本文转载于:https://dev.to/daviduzondu/serving-dynamic-html-with-pug-and-express-17h5?1如有侵犯,请联系[email protected]删除
最新教程 更多>
  • 极简设计初学者指南
    极简设计初学者指南
    我一直是干净和简单的倡导者——这是我的思维最清晰的方式。然而,就像生活中的大多数任务一样,不同的工作有不同的工具,设计也是如此。在这篇文章中,我将分享我发现的极简设计实践,这些实践有助于创建干净简单的网站、模板和图形——在有限的空间内传达必要的内容。 简单可能比复杂更难:你必须努力让你的思维清晰,使...
    编程 发布于2024-11-03
  • 了解 React 应用程序中的渲染和重新渲染:它们如何工作以及如何优化它们
    了解 React 应用程序中的渲染和重新渲染:它们如何工作以及如何优化它们
    当我们在 React 中创建应用程序时,我们经常会遇到术语渲染和重新渲染组件。虽然乍一看这似乎很简单,但当涉及不同的状态管理系统(如 useState、Redux)或当我们插入生命周期钩子(如 useEffect)时,事情会变得有趣。如果您希望您的应用程序快速高效,那么了解这些流程是关键。 ...
    编程 发布于2024-11-03
  • 如何在 Node.js 中将 JSON 文件读入服务器内存?
    如何在 Node.js 中将 JSON 文件读入服务器内存?
    在 Node.js 中将 JSON 文件读入服务器内存为了增强服务器端代码性能,您可能需要读取 JSON 对象从文件到内存以便快速访问。以下是在 Node.js 中实现此目的的方法:同步方法:对于同步文件读取,请利用 fs(文件系统)中的 readFileSync() 方法模块。此方法将文件内容作为...
    编程 发布于2024-11-03
  • 人工智能可以提供帮助
    人工智能可以提供帮助
    我刚刚意识到人工智能对开发人员有很大帮助。它不会很快接管我们的工作,因为它仍然很愚蠢,但是,如果你像我一样正在学习编程,可以用作一个很好的工具。 我要求 ChatGpt 为我准备 50 个项目来帮助我掌握 JavaScript,它带来了令人惊叹的项目,我相信当我完成这些项目时,这些项目将使我成为 J...
    编程 发布于2024-11-03
  • Shadcn UI 套件 - 管理仪表板和网站模板
    Shadcn UI 套件 - 管理仪表板和网站模板
    Shadcn UI 套件是预先设计的多功能仪表板、网站模板和组件的综合集合。它超越了 Shadcn 的标准产品,为那些不仅仅需要基础知识的人提供更先进的设计和功能。 独特的仪表板模板 Shadcn UI Kit 提供了各种精心制作的仪表板模板。目前,有 7 个仪表板模板可用,随着时间...
    编程 发布于2024-11-03
  • 如何使用正则表达式捕获多行文本块?
    如何使用正则表达式捕获多行文本块?
    匹配多行文本块的正则表达式匹配跨多行的文本可能会给正则表达式构造带来挑战。考虑以下示例文本:some Varying TEXT DSJFKDAFJKDAFJDSAKFJADSFLKDLAFKDSAF [more of the above, ending with a newline] [yep, t...
    编程 发布于2024-11-03
  • 软件开发中结构良好的日志的力量
    软件开发中结构良好的日志的力量
    日志是了解应用程序底层发生的情况的关键。 简单地使用 console.log 打印所有值并不是最有效的日志记录方法。日志的用途不仅仅是显示数据,它们还可以帮助您诊断问题、跟踪系统行为以及了解与外部 API 或服务的交互。在您的应用程序在没有用户界面的情况下运行的情况下,例如在系统之间处理和传输数据的...
    编程 发布于2024-11-03
  • 如何在单个命令行命令中执行多行Python语句?
    如何在单个命令行命令中执行多行Python语句?
    在单个命令行命令中执行多行Python语句Python -c 选项允许单行循环执行,但在命令中导入模块可能会导致语法错误。要解决此问题,请考虑以下解决方案:使用 Echo 和管道:echo -e "import sys\nfor r in range(10): print 'rob'&qu...
    编程 发布于2024-11-03
  • 查找数组/列表中的重复元素
    查找数组/列表中的重复元素
    给定一个整数数组,找到所有重复的元素。 例子: 输入:[1,2,3,4,3,2,5] 输出:[2, 3] 暗示: 您可以使用 HashSet 来跟踪您已经看到的元素。如果某个元素已在集合中,则它是重复的。为了保留顺序,请使用 LinkedHashSet 来存储重复项。 使用 HashSet 的 Ja...
    编程 发布于2024-11-03
  • JavaScript 回调何时异步?
    JavaScript 回调何时异步?
    JavaScript 回调:是否异步?JavaScript 回调并非普遍异步。在某些场景下,例如您提供的 addOne 和 simpleMap 函数的示例,代码会同步运行。浏览器中的异步 JavaScript基于回调的 AJAX 函数jQuery 中通常是异步的,因为它们涉及 XHR (XMLHtt...
    编程 发布于2024-11-03
  • 以下是根据您提供的文章内容生成的英文问答类标题:

Why does `char` behave differently from integer types in template instantiation when comparing `char`, `signed char`, and `unsigned char`?
    以下是根据您提供的文章内容生成的英文问答类标题: Why does `char` behave differently from integer types in template instantiation when comparing `char`, `signed char`, and `unsigned char`?
    char、signed char 和 unsigned char 之间的行为差​​异下面的代码可以成功编译,但 char 的行为与整数类型不同。cout << getIsTrue< isX<int8>::ikIsX >() << endl; cou...
    编程 发布于2024-11-03
  • 如何在动态生成的下拉框中设置默认选择?
    如何在动态生成的下拉框中设置默认选择?
    确定下拉框中选定的项目使用 标签创建下拉列表时,您可以可能会遇到需要将特定选项设置为默认选择的情况。这在预填写表单或允许用户编辑其设置时特别有用。在您呈现的场景中, 标记是使用 PHP 动态生成的,并且您希望根据值存储在数据库中。实现此目的的方法如下:设置选定的属性要在下拉框中设置选定的项目,您需...
    编程 发布于2024-11-03
  • Tailwind CSS:自定义配置
    Tailwind CSS:自定义配置
    介绍 Tailwind CSS 是一种流行的开源 CSS 框架,近年来在 Web 开发人员中广受欢迎。它提供了一种独特的可定制方法来创建美观且现代的用户界面。 Tailwind CSS 区别于其他 CSS 框架的关键功能之一是它的可定制配置。在这篇文章中,我们将讨论 Tailwin...
    编程 发布于2024-11-03
  • 使用 jQuery
    使用 jQuery
    什么是 jQuery? jQuery 是一个快速的 Javascript 库,其功能齐全,旨在简化 HTML 文档遍历、操作、事件处理和动画等任务。 “少写多做” MDN 状态: jQuery使得编写多行代码和tsk变得更加简洁,甚至一行代码.. 使用 jQuery 处理事件 jQuery 的另一个...
    编程 发布于2024-11-03
  • CONCAT() 如何增强 MySQL 搜索功能以实现完整名称匹配?
    CONCAT() 如何增强 MySQL 搜索功能以实现完整名称匹配?
    WHERE 子句中使用 MySQL CONCAT() 函数进行高效搜索一种常见的数据库操作是跨多列搜索数据。然而,当分别使用名字和姓氏字段搜索姓名时,可能会存在一些限制,例如捕获不完整的匹配。为了克服这个问题,可以使用 MySQL CONCAT() 函数将列组合成一个用于搜索的单个字段。这提供了更加...
    编程 发布于2024-11-03

免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。

Copyright© 2022 湘ICP备2022001581号-3