Express.js / Express.js with Template Engines

Passing Data to Templates in Express

Express.js allows you to pass data from your server to your views, allowing for dynamic content. This tutorial will cover the basics of passing data to templates in Express.

Tutorial 4 of 5 5 resources in this section

Section overview

5 resources

Covers using template engines like EJS, Pug, and Handlebars to render dynamic views.

1. Introduction

In this tutorial, we will learn how to pass data from an Express server to templates. This allows for dynamic content, meaning our web page can change based on the data it receives. By the end of this tutorial, you will be able to:

  • Understand how data is passed from Express to templates
  • Implement this functionality in your own Express applications

This tutorial assumes a basic understanding of JavaScript and familiarity with Node.js and Express.js.

2. Step-by-Step Guide

Express.js uses a feature called template engines to generate HTML with dynamic content. One popular choice is EJS (Embedded JavaScript), but others like Pug, Handlebars, and Mustache can also be used. When using a template engine, we can provide a data object from our server to the template. The template engine will then replace placeholders in our HTML with the actual data.

To pass data to templates in Express.js, you need to follow these steps:

  1. Install and set up your chosen template engine
  2. Define your data object in the server
  3. Pass the data object to the template when rendering it
  4. Use the data in the template

Best Practices and Tips

  • Always validate and sanitize data before passing it to templates to prevent XSS (Cross-Site Scripting) attacks.
  • Keep data logic and presentation logic separate. This makes your code easier to maintain and test.

3. Code Examples

Let's see an example using the EJS template engine.

First, install EJS with npm install ejs.

Then, in your server file, set EJS as the template engine:

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

app.set('view engine', 'ejs');

Now, let's define a route that passes data to a template:

app.get('/', (req, res) => {
  const data = {
    title: 'Home',
    message: 'Welcome to our website!'
  };

  res.render('index', data);
});

Here, res.render('index', data); tells Express to render the 'index' view with the provided 'data' object.

This data can be accessed in our index.ejs file:

<!DOCTYPE html>
<html>
<head>
    <title><%= title %></title>
</head>
<body>
    <h1><%= message %></h1>
</body>
</html>

In this EJS file, <%= title %> and <%= message %> are placeholders that get replaced with the values of 'title' and 'message' from our data object.

When you access the '/' route, you should see a page with the title 'Home' and a heading saying 'Welcome to our website!'.

4. Summary

In this tutorial, we've learned how to pass data from an Express server to a template, allowing for dynamic content. We've seen how to set up a template engine, define a data object, pass it to a template, and use the data in the template.

Next, you can learn more about other template engines, or how to fetch and pass data from a database.

5. Practice Exercises

  1. Create a route that passes a user's name and age to a template. Display this data in a sentence.
  2. Create a route that passes an array of blog post titles to a template. Use a loop in the template to display each title in a list.
  3. Create a route that fetches data from an API and passes it to a template. Display this data in the template.

Remember to install and set up a template engine, define and pass your data, and use the data in your templates. Happy coding!

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Color Palette Generator

Generate color palettes from images.

Use tool

JSON Formatter & Validator

Beautify, minify, and validate JSON data.

Use tool

Countdown Timer Generator

Create customizable countdown timers for websites.

Use tool

CSS Minifier & Formatter

Clean and compress CSS files.

Use tool

Random Name Generator

Generate realistic names with customizable options.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help