Input mixin with Pug

Exploring ways that pug can help reduce code with templating and how it really shines for rapid prototyping.

This definitely isn't a Pug crash course, nor is it related at all to small dogs. The purpose of this post is to capture the basic setup process for reusable, dynamic code snippets for form fields using pug mixins. It's written with the assumption that you have some basic knowledge about pug or HTML preprocessors.

Prerequisites

Like I said... Pug. You should probably at least know what pug is.


Create a pug mixin

With the mixin named "input", we'll add a couple of variables to make sure the output has unique values, is accessible, and is easy to use.

  • id: A string that will be used for the input id and the for attribute on the label.

  • name: A string for the label name.

  • required: A boolean to show some attributes and content conditionally when true.


Building the mixin out

First, add the label's for attribute variable and the label name.

Next, add the id attribute variable, and then &attributes(attributes) to the end of the input. This will allow us to add attributes on the fly when using the mixin.


Using the mixin

The output


Adding conditions

As you can see in the output above, the input is required. This will work for a lot of cases, but of course, we'll want the ability to change this.

Add a condition for required attributes


Putting it all together

Go ahead and add a few bells, whistles, and niceties to make this thing super flexible and reusable.

Usage samples

The output

About the author