Pug Template Engine - Mixin vs Include vs Extends

In this article we explain when to use include , mixin and extends features of the pug template engine.

Include

Include allows you to embed a pug template into another pug template.

Keep these embeddable pug templates focused and with static content since Include will not allow you to pass parameters to them.

Extract static content into pug template. Use include to embed them.

doctype html
html
  head
    include includes/styles.pug
  body
    p Hello World
    include includes/scripts.pug

Mixin

Use Mixin when you want to create reusable Html pieces.

Since Mixin accepts parameters they are ideal as footprints for customizable html components.

// Component item
mixin itemList(item)
  li.item= item

// Component list
mixin list(items)
  ul
    each item in items
      +itemList(item)

// Display items
- const items = ['potatoes', 'tomatoes', 'cucumber', 'carrots']
+list(items)

Mixin has also access to attributes property.

This becomes really handy for separating Html attribute values from your data.

mixin link(name)
  - const { className, url } = attributes
  // The values in attributes by default are already escaped!
  // You should use != to avoid escaping them a second time.
  a(class!=className href!=url) #{name}

- const myTitleValue = 'My blog'
+link(myTitleValue)(className="btn" url="devlimbo.com")

If you have separate your mixins into their own folder, you must include them first.

include mixins/link

- const myTitleValue = 'My blog'
+link(myTitleValue)(className="btn" url="devlimbo.com")

Extends & Block

You should use Extends and Block for creating abstract layouts.

Abstract layouts are footprints with block placeholders. Block placeholders can have predefined content.

Any pug template can act as an abstract layout.

Use the block keyword to set block placeholders.

html
  block head
    script(src='/vendor/jquery.js')
  body
    block content
      p This is the prefefined content.

    block footer

Templates extending your abstract layouts can replace(default), append or prepend block placeholders.

extends layout/html-base.pug

block append head
  script(src='/vendor/three.js')

block content
  p Article A
  p Article B
  p Article C

block footer
    p DevLimbo©2019

Applying this previous template to the Html pug template results into:

  html
    script(src='/vendor/jquery.js')
    script(src='/vendor/three.js')
  body
      p Article A
      p Article B
      p Article C

    p DevLimbo©2019

Conclusion

Pug template engine provide us with powerful tools to make our pages clean and maintanable.

In this article we have explored the differences between mixin , include and extends features that Pug template engine provides.

Use them wisely to avoid spagetti html soup.