33

I would like to set a class on the body tag by declaring a variable in a template that extends a base layout.

When I try, the body_class variable is undefined in the layout.

It appears the layout is executed before the extending template, or they are executed in different scopes or something.

Is there another way? Would a mixin work here?

_layout.jade:

doctype html
html(lang="en-au")
    head
        meta(charset="utf-8")
        block css
    body(class=(body_class || "it-did-not-work"))
        block header
        block content
        block footer

home.jade:

var body_class = 'i-am-the-home-page'
extends _layout
block header
    h1 home
Mike Causer
  • 8,196
  • 2
  • 43
  • 63

1 Answers1

87

Ah ha! Figured it out.

Create a block at the top of the base layout and add your variables in there.

_layout.jade:

block variables
doctype html
html(lang="en-au")
    head
        meta(charset="utf-8")
        block css
    body(class=(body_class || "it-did-not-work"))
        block header
        block content
        block footer

home.jade:

extends _layout
block variables
    - var body_class = 'i-am-the-home-page'
block header
    h1 home
Mike Causer
  • 8,196
  • 2
  • 43
  • 63
  • 2
    thank you sir, exactly what I was looking for. So the scope is on the root template being extended? – undefinederror Nov 14 '15 at 13:05
  • 3
    This is missing a dash before the var statement. It should be `- var body_class = 'i-am-the-home-page'`. Otherwise the code will not be compiled as JavaScript. – nomad Jan 03 '17 at 04:31
  • 2
    I found this, which has examples of how to actually implement this. I found it helpful - https://gist.github.com/viktorbezdek/9665226 – Mote Zart Nov 07 '19 at 00:30
  • This should totally be included in the Pug's documentation. There's no way that this is an obvious usage of a block. – Lazar Ljubenović Nov 14 '19 at 11:16