Using Templating Engines
Deslize para mostrar o menu
To render dynamic HTML in your Express.js applications, you use a templating engine. Templating engines allow you to embed variables and logic directly into your HTML files, making it easy to create dynamic content that changes depending on data from your server.
Begin by installing a templating engine such as Pug. In your project directory, run:
npm install pug
Next, set up your Express.js app to use Pug as the view engine. This tells Express to use Pug templates for rendering views.
Here is a basic setup:
const express = require('express');
const app = express();
// Set 'views' directory for template files
app.set('views', './views');
// Set Pug as the view engine
app.set('view engine', 'pug');
// Define a route that renders a template with variables
app.get('/', (req, res) => {
res.render('index', { title: 'Welcome', message: 'Hello, Express with Pug!' });
});
app.listen(3000, () => {
console.log('Server running on http://localhost:3000');
});
You also need a Pug template file. Create a directory called views in your project root, and inside it, add a file named index.pug:
doctype html
html
head
title= title
body
h1= message
p This page is rendered using Pug templating engine.
When you visit http://localhost:3000, Express renders the index.pug template, passing it the title and message variables. Pug then generates the final HTML by replacing the variables with their values.
Templating engines work by allowing you to write templates that mix static HTML with placeholders for dynamic data. When a request comes in, Express can call res.render() to process a template file, inject the data you provide, and generate the final HTML response.
You pass data to a template by providing an object as the second argument to res.render(). The keys in this object become variables available inside your template. This approach keeps your application logic separate from your HTML layout, making your code cleaner and easier to maintain.
With templating engines, you can reuse common layouts, include partials, and avoid manual string concatenation. This helps you build complex, data-driven pages efficiently.
Obrigado pelo seu feedback!
Pergunte à IA
Pergunte à IA
Pergunte o que quiser ou experimente uma das perguntas sugeridas para iniciar nosso bate-papo