Express es capaz de manejar motores de plantillas del lado del servidor. Los motores de plantilla nos permiten agregar datos a una vista y generar HTML de forma dinámica.
Express es capaz de manejar motores de plantillas del lado del servidor.
Los motores de plantilla nos permiten agregar datos a una vista y generar HTML de forma dinámica.
Express usa Jade como predeterminado. Jade es la versión antigua de Pug, específicamente Pug 1.0.
El nombre se cambió de Jade a Pug debido a un problema de marca registrada en 2016, cuando el proyecto lanzó la versión 2. Todavía puedes usar Jade, también conocido como Pug 1.0, pero en el futuro, es mejor usar Pug 2.0
Aunque la última versión de Jade tiene 3 años (en el momento de escribir este artículo, verano de 2018), sigue siendo la predeterminada en Express por razones de compatibilidad con versiones anteriores.
En cualquier proyecto nuevo, debe usar Pug u otro motor de su elección. El sitio oficial de Pug eshttps://pugjs.org/.
Puede usar muchos motores de plantilla diferentes, incluidos Pug, Handlebars, Moustache, EJS y más.
Usando Pug
Para usar Pug primero debemos instalarlo:
npm install pug
y al inicializar la aplicación Express, necesitamos configurarla:
const express = require('express')
const app = express()
app.set('view engine', 'pug')
Ahora podemos empezar a escribir nuestras plantillas en.pug
archivos.
Crear una vista de acerca de:
app.get('/about', (req, res) => {
res.render('about')
})
y la plantilla enviews/about.pug
:
p Hello from FlavioThis 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:
- Express, a popular Node.js Framework
- Retrieve the GET query string parameters using Express
- Validating input in Express using express-validator
- Express Templates
- Serving Static Assets with Express
- Send a JSON response using Express
- Express Sessions
- Send a response using Express
- Send files using Express
- Sanitizing input in Express using express-validator
- Routing in Express
- An Express HTTPS server with a self-signed certificate
- Express, Request Parameters
- Retrieve the POST query parameters using Express
- Handling redirects with Express
- Express Middleware
- Setup Let's Encrypt for Express
- Work with HTTP headers in Express
- Handling forms in Express
- Handling file uploads in forms using Express
- Handling CORS in Express
- Manage Cookies with Express