Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Jade, how can I declare a body class in an extended template?

Tags:

pug

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.

like image 806
Frode Avatar asked Feb 09 '12 13:02

Frode


3 Answers

Jade supports ruby like string interpretation

In your layout

- var bodyClass = '';
block vars
body(class='#{bodyClass}')
  block content

In your view files

extends layout
block vars
  - var bodyClass = 'my-page';
block content
  p Hello World!
like image 129
Mohsen Avatar answered Oct 28 '22 23:10

Mohsen


You can manipulate variables in parent scope, so this solution is also possible:

In your layout

- var bodyClasses = [];
block beforeBody

body(class=bodyClasses)
  block content

In your view files

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.

like image 23
Stephan Hoyer Avatar answered Oct 28 '22 21:10

Stephan Hoyer


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.

like image 4
mna Avatar answered Oct 28 '22 23:10

mna