how to pass variables between jade templates

I am using a template as a base, and want it to be aware of some variables set in the page that is using it...

File: template.jade

vars = vars || {some:"variables"}
!!! 5
head
    title vars.some

File: page.jade

vars = {some:"things"} //- this does not get used from within template.jade
extends template

I want the compiled page.jade to have a title "things"


I find solution here

pass block with variables

template.jade:

!!!
html
  block vars
  head
      title #{pageTitle} - default www title
  body

page.jade

extends template
block vars
  - var pageTitle = 'Home'

You can use blocks:

template.jade:

!!! 5
head
    block title
        title variables

page.jade:

extends template
block title
    title things

Else you have to define the variables in your script (for example express). As far as I know, variables can only be passed around via includes, but not upwards to the layout (template.jade in your case).


I thought that blocks wouldn't work for me because I needed to use the variable in multiple places.

// base.jade
pageTitleVar = "Parent's Title"
!!!
title !{pageTitleVar}
h1 !{pageTitleVar}

Turns out you can actually specify the same block twice in the parent template and whatever the child template passes to it gets duplicated.

// base.jade
pageTitleVar = "Parent's Title"
!!!
title
  block pageTitleBlock
    !{pageTitleVar}
h1
  block pageTitleBlock
    !{pageTitleVar}

// child.jade
extends base
pageTitleVar = "Child's Title"
block pageTitleBlock
   !{pageTitleVar}

Blocks FTW


A great and commented solution to add title like this:
"My Project - The Page".

Or just this:
"My Project"

template: template.jade

doctype 5
html(lang="en")
head
    //- setting the page title to be dynamic
    block vars
        - var defaultTitle = "My Project"
        - var pageTitle = pageTitle
    title #{defaultTitle}#{pageTitle}

some page: page.jade

extends base
//- custom page title
block append vars
    pageTitle = " - The Page"