9

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.

Peter David Carter
  • 2,548
  • 8
  • 25
  • 44
A Macdonald
  • 814
  • 1
  • 7
  • 10

1 Answers1

16

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>
David Weldon
  • 63,632
  • 11
  • 148
  • 146
  • so you're saying the include will not have scope on that variable? I would like to avoid a mixin given the contents of my actual includes/header.jade file - my example was quite simplified! But if you are saying I can't inherit the variable like this I guess I have no choice – A Macdonald Feb 23 '13 at 01:02
  • actually it works just fine :) thanks - definitely using mixins more - not as bad as I thought - thanks again – A Macdonald Feb 23 '13 at 01:09
  • Yeah I realized I didn't actually answer your question. So your original code works fine if you just run `jade master.jade` - you'll get an error if you compile `includes/header.jade`. Personally I'm a huge fan of mixins and use them as much as I can. I think it's the superior solution even in this case since you can specify what arguments the mixin can take, and jade won't complain if you ask it to compile the include. – David Weldon Feb 23 '13 at 01:28
  • ah so that's the answer! my command `jade -P jade --out html` of course compiles all files inside the jade folder including the includes folder... still I do prefer the mixin also – A Macdonald Feb 23 '13 at 01:32
  • you can use '+' instead of 'mixin' :) – BotanMan Nov 27 '15 at 09:16