Oral  Brekke

Oral Brekke

1625153280

Building Page Templates in ExpressJS with Handlebars

Writing HTML sucks, thus we should do everything to minimize the time we spend writing it as much as possible. Thus, we have  Handlebars: a lightweight templating system for Node. Handlebars allows us to avoid repetitive code by compiling the final DOM structure of our site via logic, typically compiled by task runners such as Grunt or Gulp.

If you’re involved in any sort of Node development, you’re probably already familiar with Handlebars to a degree. I thought I was, but it isn’t until we need to start a new project from scratch that we realize that we totally forgot the configuration process we took last time. That’s why I’m here.

Let’s have a quick refresher on the parts that make up Handlebars

  • Layouts are the most ambiguous high-level layer; these are commonly used to set underlying page metadata as well as general layout (for lack of a better term).
  • Pages are templates which equate to one type of page. For example, the ‘post’ page on this site is unique from, say, the homepage. Because all posts share elements with one another, hundreds of posts share this same template.
  • Partials are snippets which can be shared between pages, such as navigation.
  • A Context is content which is passed to templates and result in being the page’s content
  • Helpers are the closest we get to logic in Handlebars: these allow us to display or omit content based on conditionals such as if statements. For example: showing an author’s avatar only if they have uploaded an image.

#nodejs #frontend #expressjs #javascript #node

Building Page Templates in ExpressJS with Handlebars