Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Mixins

A mixin is a named piece of markup that you declare once and call as many times as you like. It is like a function: it can take arguments and produce different markup. Mixins save you from copying identical cards, buttons and blocks.

Declaring and calling

A mixin is declared with the word mixin and a name, and its markup goes below with an indent. A call is the mixin name with a plus in front. In src/index.pug:

mixin hours
  p.hours Every day from 8:00 to 20:00.
 
+hours
+hours

The declaration itself outputs nothing. Each +hours call inserts the mixin's markup:

<p class="hours">Every day from 8:00 to 20:00.</p>
<p class="hours">Every day from 8:00 to 20:00.</p>

Arguments

Arguments are listed in parentheses, as in a JavaScript function. A drink card with a name and a price:

mixin drink(name, price)
  .card
    h3= name
    p.price $#{price}
 
+drink("Cappuccino", 3)
+drink("Espresso", 2)

The same markup received different data:

<div class="card">
  <h3>Cappuccino</h3>
  <p class="price">$3</p>
</div>
<div class="card">
  <h3>Espresso</h3>
  <p class="price">$2</p>
</div>

An argument can have a default value: mixin drink(name, price = 3) — then the call +drink("Latte") outputs the price $3.

A mixin in a loop

Mixins work well with each. Take the menu array that build.js passes since the lesson on iteration:

mixin drink(name, price)
  .card
    h3= name
    p.price $#{price}
 
each item in menu
  +drink(item.name, item.price)

The loop calls the mixin for every drink:

<div class="card">
  <h3>Espresso</h3>
  <p class="price">$2</p>
</div>
<div class="card">
  <h3>Cappuccino</h3>
  <p class="price">$3</p>
</div>
<div class="card">
  <h3>Hot chocolate</h3>
  <p class="price">$3</p>
</div>

Content inside the call

You can write indented markup under a mixin call. Inside the mixin it is available as block:

mixin card(title)
  .card
    h3= title
    if block
      block
    else
      p Description coming soon.
 
+card("Cappuccino")
  p Espresso with steamed milk foam.
+card("Raf")

if block checks whether content was passed. The cappuccino has some, the raf does not, so the default text is output:

<div class="card">
  <h3>Cappuccino</h3>
  <p>Espresso with steamed milk foam.</p>
</div>
<div class="card">
  <h3>Raf</h3>
  <p>Description coming soon.</p>
</div>

Where to keep mixins

Once there are many mixins, they move to a separate file, such as src/mixins.pug, which every page includes. The next lesson shows how to include files.

Common mistake

Calling a mixin without the plus:

mixin drink(name)
  p= name
 
drink("Cappuccino")

Without + Pug treats drink as an ordinary tag and the parentheses as its attributes:

<drink Cappuccino="Cappuccino"></drink>

A mixin is always called with +: +drink("Cappuccino").

Thanks for reading!

Donate to the site — we work hard for you.