如何使用Pug模板引擎
- 哈巴狗简介
- 哈巴狗看起来如何?
- 安装哈巴狗
- 将Pug设置为Express中的模板引擎
- 您的第一个帕格模板
- 在Pug中内插变量
- 插值函数返回值
- 向元素添加id和class属性
- 设定文件类型
- 元标记
- 添加脚本和样式
- 内联脚本
- 循环
- 有条件的
- 设定变数
- 递增变量
- 将变量分配给元素值
- 遍历变量
- 包括其他Pug文件
- 定义块
- 扩展基本模板
- 评论
哈巴狗简介
哈巴狗是什么?它是服务器端Node.js应用程序的模板引擎。
Express能够处理服务器端模板引擎。模板引擎使我们能够向视图添加数据并动态生成HTML。
帕格是旧事物的新名称。它是玉2.0。
由于商标问题,该项目在2016年发布了版本2,因此名称从Jade更改为Pug。您仍然可以使用Jade(aka Pug 1.0),但最好继续使用Pug 2.0。
另请参阅玉和哈巴狗之间的区别
Express使用Jade作为默认设置。如上所述,Jade是Pug的旧版本-特别是Pug 1.0。
尽管Jade的最新版本已经3年了(在撰写本文时,2018年夏季),但出于向后兼容的原因,它仍然是Express中的默认版本。
帕格的官方网站是https://pugjs.org/。
哈巴狗看起来如何?
p Hello from FlavioThis template will create a p
tag with the content Hello from Flavio
.
As you can see, Pug is quite special. It takes the tag name as the first thing in a line, and the rest is the content that goes inside it.
If you are used to template engines that use HTML and interpolate variables; like Handlebars (described next), you might run into issues, especially when you need to convert existing HTML to Pug. This online converter from HTML to Jade (which is very similar, but a little different to Pug) will be a great help: https://jsonformatter.org/html-to-jade
Install Pug
Installing Pug is as simple as running npm install
:
npm install pug
Setup Pug to be the template engine in Express
and when initializing the Express app, we need to set it:
const path = require('path')
const express = require('express')
const app = express()
app.set('view engine', 'pug')
app.set('views', path.join(__dirname, 'views'))
Your first Pug template
Create an about view:
app.get('/about', (req, res) => {
res.render('about')
})
and the template in views/about.pug
:
p Hello from FlavioThis template will create a p
tag with the content Hello from Flavio
.
Interpolating variables in Pug
You can interpolate a variable using:
app.get('/about', (req, res) => {
res.render('about', { name: 'Flavio' })
})
p Hello from #{name}Interpolate a function return value
You can interpolate a function return value using:
app.get('/about', (req, res) => {
res.render('about', { getName: () => 'Flavio' })
})
p Hello from #{getName()}Adding id and class attributes to elements
p#title
p.titleSet the doctype
doctype htmlMeta tags
html
head
meta(charset='utf-8')
meta(http-equiv='X-UA-Compatible', content='IE=edge')
meta(name='description', content='Some description')
meta(name='viewport', content='width=device-width, initial-scale=1')Adding scripts and styles
html
head
script(src="script.js")
script(src='//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js')
link(rel='stylesheet', href='css/main.css')</code></pre>
Inline scripts
script alert('test')
script.
(function(b,o,i,l,e,r){b.GoogleAnalyticsObject=l;b[l]||(b[l]=
function(){(b[l].q=b[l].q||[]).push(arguments)});b[l].l=+new Date;
e=o.createElement(i);r=o.getElementsByTagName(i)[0];
e.src=’//www.google-analytics.com/analytics.js’;
r.parentNode.insertBefore(e,r)}(window,document,‘script’,‘ga’));
ga(‘create’,‘UA-XXXXX-X’);ga(‘send’,‘pageview’);
Loops
ul
each color in ['Red', 'Yellow', 'Blue']
li= color
ul
each color, index in [‘Red’, ‘Yellow’, ‘Blue’]
li= 'Color number ’ + index + ': ’ + color
Conditionals
if name
h2 Hello from #{name}
else
h2 Helloelse-if works too:
if name
h2 Hello from #{name}
else if anotherName
h2 Hello from #{anotherName}
else
h2 HelloAnother example:
if users.length > 2
each user in users
...Set variables
You can set variables in Pug templates:
- var name = 'Flavio'
- var age = 35
- var roger = { name: 'Roger' }
- var dogs = ['Roger', 'Syd']Incrementing variables
You can increment a numeric variable using ++
:
age++Assigning variables to element values
p= name
span.age= ageIterating over variables
You can use for
or each
, they are interchangeable and there is no difference:
for dog in dogs
li= dog
ul
each dog in dogs
li= dogYou can use .length
to get the number of items:
p There are #{values.length}while
is another kind of loop:
- var n = 0;
ul
while n <= 5
li= n++
Including other Pug files
In a Pug file you can include other Pug files:
include otherfile.pugDefining blocks
A well-organized template system will define a base template, and then all the other templates will extend from it.
Part of a template can be extended by using blocks:
html
head
script(src="script.js")
script(src='//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js')
link(rel='stylesheet', href='css/main.css')
block head
body
block body
h1 Home page
p welcome
In this case one block, body
, has some content, while head
does not. head
is intended to be used to add additional content to the heading, while the body
content is made to be overridden by other pages.
Extending a base template
A template can extend a base template by using the extends
keyword:
extends home.pugOnce this is done, you need to redefine blocks. All the content of the template must go into blocks, otherwise the engine does not know where to put them.
Example:
extends home.pug
block body
h1 Another page
p Hey!
ul
li Something
li Something else
You can redefine one or more blocks. The ones not redefined will be kept with the original template content.
Comments
Comments in Pug can be of two types: visible or invisible in the resulting HTML.
Visible
Inline:
// some commentBlock:
//
some
commentInvisible
Inline:
//- some commentBlock:
//-
some
comment
Download my free Node.js Handbook
More node tutorials:
- An introduction to the npm package manager
- Introduction to Node.js
- HTTP requests using Axios
- Where to host a Node.js app
- Interact with the Google Analytics API using Node.js
- The npx Node Package Runner
- The package.json guide
- Where does npm install the packages?
- How to update Node.js
- How to use or execute a package installed using npm
- The package-lock.json file
- Semantic Versioning using npm
- Should you commit the node_modules folder to Git?
- Update all the Node dependencies to their latest version
- Parsing JSON with Node.js
- Find the installed version of an npm package
- Node.js Streams
- Install an older version of an npm package
- Get the current folder in Node
- How to log an object in Node
- Expose functionality from a Node file using exports
- Differences between Node and the Browser
- Make an HTTP POST request using Node
- Get HTTP request body data using Node
- Node Buffers
- A brief history of Node.js
- How to install Node.js
- How much JavaScript do you need to know to use Node?
- How to use the Node.js REPL
- Node, accept arguments from the command line
- Output to the command line using Node
- Accept input from the command line in Node
- Uninstalling npm packages with `npm uninstall`
- npm global or local packages
- npm dependencies and devDependencies
- The Node.js Event Loop
- Understanding process.nextTick()
- Understanding setImmediate()
- The Node Event emitter
- Build an HTTP Server
- Making HTTP requests with Node
- The Node fs module
- HTTP requests in Node using Axios
- Reading files with Node
- Node File Paths
- Writing files with Node
- Node file stats
- Working with file descriptors in Node
- Working with folders in Node
- The Node path module
- The Node http module
- Using WebSockets with Node.js
- The basics of working with MySQL and Node
- Error handling in Node.js
- The Pug Guide
- How to read environment variables from Node.js
- How to exit from a Node.js program
- The Node os module
- The Node events module
- Node, the difference between development and production
- How to check if a file exists in Node.js
- How to create an empty file in Node.js
- How to remove a file with Node.js
- How to get the last updated date of a file using Node.js
- How to determine if a date is today in JavaScript
- How to write a JSON object to file in Node.js
- Why should you use Node.js in your next project?
- Run a web server from any folder
- How to use MongoDB with Node.js
- Use the Chrome DevTools to debug a Node.js app
- What is pnpm?
- The Node.js Runtime v8 options list
- How to fix the "Missing write access" error when using npm
- How to enable ES Modules in Node.js
- How to spawn a child process with Node.js
- How to get both parsed body and raw body in Express
- How to handle file uploads in Node.js
- What are peer dependencies in a Node module?
- How to write a CSV file with Node.js
- How to read a CSV file with Node.js
- The Node Core Modules
- Incrementing multiple folders numbers at once using Node.js
- How to print a canvas to a data URL
- How to create and save an image with Node.js and Canvas
- How to download an image using Node.js
- How to mass rename files in Node.js
- How to get the names of all the files in a folder in Node
- How to use promises and await with Node.js callback-based functions
- How to test an npm package locally
- How to check the current Node.js version at runtime
- How to use Sequelize to interact with PostgreSQL
- Serve an HTML page using Node.js
- How to solve the `util.pump is not a function` error in Node.js