How to reduce code duplication in jade?

How to reduce code duplication in jade?

Problem

I am a beginner to both web development and node.js. I am trying to build a very basic news website with node.js and express. In the home page, I hope to display some featured news, and in the page “news” I expect to display all the news.

It makes sense that the home page and the “news” page can share the jade code to display news. Using the same routes and db node.js functions to handle news listing in both places seems straightforward to me. I wonder whether there is a good way to share code and reduce code duplication in jade (perhaps like the concept “partial” in ruby on rails)?

Any help or reference links are welcomed. Thanks!

Problem courtesy of: Jeff Jia

Solution

Jade has Includes:

html
  include includes/head
  body
    h1 My Site
    p Welcome to my super amazing site.
    include includes/foot

Also you can use Mixins when possible, to reduce the amount of code you need to write:

mixin list
  ul
    li foo
    li bar
    li baz

h2 Groceries
mixin list
Solution courtesy of: fardjad

Discussion

Leave a Reply

Your email address will not be published. Required fields are marked *