Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jade templating, variable scope in includes

Tags:

node.js

pug

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.

like image 256
A Macdonald Avatar asked Feb 23 '13 00:02

A Macdonald


1 Answers

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>
like image 61
David Weldon Avatar answered Nov 12 '22 08:11

David Weldon