Filters
A filter processes a piece of text with another program at build time and puts the result into the HTML. The most common case is Markdown: long text is easier to write in it than with Pug tags. A filter is written as a colon and a name: :markdown-it.
Installing a filter
Pug cannot turn Markdown into HTML by itself. Filters come as separate packages named jstransformer- plus the filter name. Install the Markdown filter:
npm install --save-dev jstransformer-markdown-itPug finds the package by itself: the filter name markdown-it matches the end of the package name. You do not need to change build.js.
Markdown inside a template
The "About us" block on the home page. In src/index.pug:
section
:markdown-it
## Our story
We roast our beans **ourselves**.The text under the filter is indented one level. The hashes became a heading, the asterisks bold text:
<section><h2>Our story</h2>
<p>We roast our beans <strong>ourselves</strong>.</p>
</section>The empty line before </section> is a line break left by Markdown; it is not visible on the page.
Markdown from a separate file
Long texts are easier to keep in their own files. Create src/about.md:
## About us
Morning Café opened in **2015**.And include it with a filter in src/index.pug:
section
include:markdown-it about.mdThe file is read and turned into HTML at build time:
<section><h2>About us</h2>
<p>Morning Café opened in <strong>2015</strong>.</p>
</section>This way the "About us" text can be edited by someone who does not know Pug.
When to use filters
| Task | Solution |
|---|---|
| Long text with headings and lists | The :markdown-it filter |
| A little CSS or JavaScript | A dot block: style. or script. |
| Repeated markup | A mixin, not a filter |
Other languages have jstransformer-... packages too, but Markdown is enough for most sites.
Common mistake
Inserting variables into text under a filter:
- const cafe = "Morning Café"
:markdown-it
Welcome to #{cafe}The filter runs while the template is being parsed, before any data exists, so the insertion stays as it is:
<p>Welcome to #{cafe}</p>Write only fixed text inside filters. If you need data, output it with Pug tags next to the filter.