快递模板

Express能够处理服务器端模板引擎。模板引擎使我们能够向视图添加数据,并动态生成HTML。

Express能够处理服务器端模板引擎。

模板引擎使我们能够向视图添加数据,并动态生成HTML。

Express使用Jade作为默认设置。 Jade是Pug的旧版本,特别是Pug 1.0。

由于该项目在2016年发布了版本2,由于商标问题,名称从Jade更改为Pug。您仍然可以使用Jade,也就是Pug 1.0,但今后最好使用Pug 2.0

尽管Jade的最新版本已经3年了(在撰写本文时,2018年夏季),但出于向后兼容的原因,它仍然是Express中的默认版本。

在任何新项目中,都应使用Pug或您选择的其他引擎。哈巴狗的官方网站是https://pugjs.org/

您可以使用许多不同的模板引擎,包括Pug,车把,Mustache,EJS等。

使用哈巴狗

要使用Pug,我们必须首先安装它:

npm install pug

并且在初始化Express应用时,我们需要对其进行设置:

const express = require('express')
const app = express()
app.set('view engine', 'pug')

现在,我们可以开始在.pug文件。

创建一个关于视图:

app.get('/about', (req, res) => {
  res.render('about')
})

和模板在views/about.pug

p Hello from Flavio

This template will create a p tag with the content Hello from Flavio.

You can interpolate a variable using

app.get('/about', (req, res) => {
  res.render('about', { name: 'Flavio' })
})
p Hello from #{name}

This is a very short introduction to Pug, in the context of using it with Express. Look at the Pug guide for more information on how to use Pug.

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 than Pug) will be a great help: https://jsonformatter.org/html-to-jade

Also see the differences between Jade and Pug

Using Handlebars

Let’s try and use Handlebars instead of Pug.

You can install it using npm install hbs.

Put an about.hbs template file in the views/ folder:

Hello from {{name}}

and then use this Express configuration to serve it on /about:

const express = require('express')
const app = express()
const hbs = require('hbs')

app.set(‘view engine’, ‘hbs’) app.set(‘views’, path.join(__dirname, ‘views’))

app.get(’/about’, (req, res) => { res.render(‘about’, { name: ‘Flavio’ }) })

app.listen(3000, () => console.log(‘Server ready’))

You can also render a React application server-side, using the express-react-views package.

Start with npm install express-react-views react react-dom.

Now instead of requiring hbs we require express-react-views and use that as the engine, using jsx files:

const express = require('express')
const app = express()

app.set(‘view engine’, ‘jsx’) app.engine(‘jsx’, require(‘express-react-views’).createEngine())

app.get(’/about’, (req, res) => { res.render(‘about’, { name: ‘Flavio’ }) })

app.listen(3000, () => console.log(‘Server ready’))

Just put an about.jsx file in views/, and calling /about should present you an “Hello from Flavio” string:

const React = require('react')

class HelloMessage extends React.Component { render() { return <div>Hello from {this.props.name}</div> } }

module.exports = HelloMessage

Download my free Express.js Handbook


More express tutorials: