Book Image

Mastering Web Application Development with Express

By : Alexandru Vladutu
Book Image

Mastering Web Application Development with Express

By: Alexandru Vladutu

Overview of this book

Table of Contents (18 chapters)
Mastering Web Application Development with Express
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

View helpers and application-level data


Things tend to get messy when including a lot of control-flow statements into our templates, such as if statements. You might have even noticed this from some of the previous examples.

The first step to clean this up would be to extract the logic from the templates into functions (view helpers). They can reside either in the route handler or, better yet, in a separate folder. An example of such a function would be the one used to construct the full name of a user:

function getFullName(firstName, lastName) {
  return firstName + ' ' + lastName;
}

Now, we can pass this function as a local variable to the template and invoke it from there, as shown in the following snippet:

// route handler  
res.render('index', {
  user: users[parseInt(req.params.index) || 0],
  getFullName: getFullName
});
// ejs template
<%= getFullName(user.firstName, user.lastName) %>

It's a bit better now since we removed that inline logic, and we can reuse this function for multiple...