A Macdonald A Macdonald - 6 months ago 40
Node.js Question

Jade templating, variable scope in includes

I am using Jade (without Express, just for static HTML templating) - which I understood as able to create partials, meaning scope is not an issue, but this doesn't seem to be the case and I can find no reference to this use-case.

master.jade

!!! 5
html
block vars
- var slug= 'home'
head
block pagetitle
title Static HTML
link(rel='stylesheet', href='css/styles.css')
body(class= slug)
.wrapper
include includes/header


includes/header.jade

.header
ul
li(class= slug)


I have tried syntax variants including
#{slug}
and always get the error "slug is not defined" within the
includes/header.jade
file - is it possible to do this?

EDIT: So the answer as given by Dave Weldon in the comments below is that the variable is available when included in master.jade but my build command compiled all jade files including the includes on their own, at which point the variable is of course not defined.

Answer

You could accomplish this with a mixin like so:

master.jade

include includes/header

!!!
html
  block vars
  - var slug= 'home'
  head
    block pagetitle
      title Static HTML
    link(rel='stylesheet', href='css/styles.css')
  body(class= slug)
    .wrapper
      mixin header(slug)

includes/header.jade

mixin header(klass)
  .header
    ul
      li(class= klass)

When compiled:

<!DOCTYPE html>
<html>
  <head>
    <title>Static HTML</title>
    <link rel="stylesheet" href="css/styles.css">
  </head>
  <body class="home">
    <div class="wrapper">
      <div class="header">
        <ul>
          <li class="home"></li>
        </ul>
      </div>
    </div>
  </body>
</html>