Benjamin Hollon
Posted on February 26, 2021
To me, one of the most tedious parts of writing HTML is creating forms. So now that I've started using PugJS as a templating engine and to speed up my development process, I naturally wondered if I could use it to streamline the form-creation process while keeping everything accessible.
I came up with this mixin that should cover most use cases:
mixin form(method, action, inputs, submitLabel)
form(method=method action=action)
if inputs
each input in inputs
case input.type
when 'textarea'
label #{input.label}
textarea(placeholder=input.placeholder required=input.required name=input.name id=input.id class=input.class maxlength=input.maxlength autofocus=input.autofocus autocomplete = input.autocomplete)
when 'checkbox'
when 'radio'
label
input(type=input.type name=input.name id=input.id class=input.class required=input.required)
| #{" " + input.label}
default
label #{input.label}
input(type=input.type min=input.min max=input.max multiple=input.multiple pattern=input.pattern step=input.step height=input.height width=input.width placeholder=input.placeholder required=input.required name=input.name id=input.id class=input.class maxlength=input.maxlength autofocus=input.autofocus autocomplete = input.autocomplete)
input(type="submit" value=submitLabel)
It looks a bit unwieldy at first, but all those attributes just help me cover all the different input types. Now that I've made this (I can use an include to use the same mixin on all the pages it's needed), all I need to do is this to make a form:
+form
Now, all this makes is an empty form element with a submit button. Here's a more complete example with a couple of basic input elements:
+form("post", "", [
{
label: 'Your Full Name',
name: 'name',
type: 'text',
placeholder: 'John Doe',
required: true,
autofocus: true
},
{
label: 'Your Email',
name: 'email',
type: 'email',
placeholder: 'john@doe.com',
required: true
},
{
label: 'I agree with the Terms & Conditions',
type: 'checkbox',
required: true
}
], "Go!")
Which gives me this neat tidy form, easy as pie:
Have fun. :)
Posted on February 26, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.