ExpressはデフォルトとしてJadeを使用します。 JadeはPugの古いバージョン、特にPug1.0です。

プロジェクトがバージョン2をリリースした2016年に商標の問題が発生したため、名前がJadeからPugに変更されました。Jade、別名Pug 1.0は引き続き使用できますが、今後はPug2.0を使用することをお勧めします。






npm install pug


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



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


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:

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 {}</div> } }

module.exports = HelloMessage

Download my free Express.js Handbook

More express tutorials: