Using the Jade template engine, I want the ability to optionally declare classes to body tags, in templates that extends another.
layout.jade
!!! 5
html(lang='en')
head
block title
meta(charset='utf-8')
link(rel='stylesheet', href='/stylesheets/style.css')
block addhead
block body
div#wrap
header
div#header_content
p
a(href='/')
img(src='/images/logo.png', alt='Template-e-o')
div.hr.red
br(style='clear:both;')
div#content
block content
br(style='clear:both;')
index.jade
extends layout
block title
title bidi
block body
body.index
block content
p ’ello govna.
This is not working.
Jade supports ruby like string interpretation
- var bodyClass = '';
block vars
body(class='#{bodyClass}')
block content
extends layout
block vars
- var bodyClass = 'my-page';
block content
p Hello World!
You can manipulate variables in parent scope, so this solution is also possible:
- var bodyClasses = [];
block beforeBody
body(class=bodyClasses)
block content
extends layout
block beforeBody
- bodyClasses.push('my-page')
block content
p Hello World!
Doing so lets you add multiple classes in different levels of your layout.
Ok, the block body
statement is just a block with the name body, so in your layout you don't have a body
tag included, it must be added in index.jade (which you try to do). However, in your index.jade, you replace the block content with only body.index (which, I guess - since I'm not on my dev computer and can't try it out right now - renders OK but takes out the whole content, you end up with just an empty body, although it should have the class='index' attribute).
What you could try is this (in index.jade):
block prepend body
body.index
But I'm not sure if the rest of your layout.jade (div#wrap) will render correctly under body (I doubt it).
What I would recommend, if it's really just a matter of adding a conditional class on the body, is something like this in layout.jade (instead of block body):
body(class=myClassLocalVar)
Where myClassLocalVar is specified in your .render call (res.render('index', {myClassLocalVar: 'theClass'});
). myClassLocalVar can even be an array, and jade will assign all the classes in the array to your body.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With