Mixins in Jade: Node.js

Mixins in Jade are much like functions/methods in many other programming languages.

Basically, if you’re repeating your code at many places, you could place that code inside a mixin and replace your code with the mixin call. This would make your code cleaner and maintainable over long run.

Related Read: Loops and Conditions In Jade: Node.js

mixins in Jade
mixin.jade

mixin fetch(users)
 ul
 -each user in users
  li= user

This would get the users as argument – loop through each user and put the individual user in the list item of an unordered list.

include in index file: Jade
index.jade

include mixin

- users = ["Apple", "IBM"];
mixin fetch(users)



- users = ["Google", "Amazon"]; mixin fetch(users)

Here we have included the mixin.jade file, and now use our fetch mixin and pass-in our array variable, which is converted into an unordered list of items and output on the browser.

Mixins in Jade: Node.js



YouTube Link: https://www.youtube.com/watch?v=g6DPkVpfauc [Watch the Video In Full Screen.]



Note: Clearly, in real-time applications the array or object come from the database.
Example: You might encounter the situation to list out all the users in your list and list of all the participating companies. Or list of all companies someone has worked at. In such cases you’ll get an array of objects which you need to out put to the user in a well formatted manner. In situations like this, mixins are a great tool to have, to avoid the necesity to repeat your code allover your application.

Have all your mixins in a single file and then include that file wherever you are calling your mixins.