cmonsqpr
cmonsqpr

Reputation: 603

nodejs jade conditional extend

I would like to make my Jade page extend different layouts, depending on a condition. So my code looks like this:

if myConditionVariable
  extends layout1
else
  extends layout2  
block content
  p here goes my content!

Now this does not work. It seems as if only the last defined extends will be respected, regardless of the conditions. I also tried dynamically defining the templatename, such as

extends myLayoutNameVariable

and set the myLayoutNameVariable in different manners (express dynamic helper function, set it as var, local var etc...)

Is there any other solution for conditional layouts or can someone tell me what i am doing wrong?

Cheers, simon

Upvotes: 10

Views: 5572

Answers (4)

atc
atc

Reputation: 605

I hope it's not too late but i ran across this issue and I think I figured out a workaround:

  1. Make a layout.jade that conditionaly includes both layouts:

    layout.jade:
    
    if conditionalVariable
        include firstLayout.jade
    else
        include otherLayout
    
  2. In your view, extend layout.jade, and define conditionalVariable in the controller (true/false):

    view.jade:
    
    extends layout
    
    block content
        p here goes my content!
    
  3. Disco!

Upvotes: 6

Andrew Theken
Andrew Theken

Reputation: 3480

So, a slightly less intrusive way to deal with this is to change the layout itself.

I added a bit of middleware, and the rest flows..

app.use(function(req, res, next){
    res.locals.isAjax = req.headers['x-requested-with'] && 
        req.headers['x-requested-with'] === 'XMLHttpRequest';
    next();
});

Now that this is set, "isAjax" is available to jade.

In my "layout.jade" (the template you will extend from), I do this:

- if(!isAjax)
  doctype 5
    html
      head
      body
        block content
        block scripts
- else
  block content
  block scripts

I have stripped out the other elements of the full layout.jade for (hopefully) clarity.

Finally, my normal views that extend layout.jade work without modification (this jade template includes both cases).

extends layout.jade
  .container.
     This is text will be wrapped for a non-ajax request, 
     but not for an ajax request.

Upvotes: 11

Pickels
Pickels

Reputation: 34632

This seems to be an issue that's still open on github.

Upvotes: 8

optikfluffel
optikfluffel

Reputation: 2738

Can you do something like:

if myConditionVariable
  p test

?

If not, do you pass myConditionVariable correct when you tell to render that view? A short example for this:

app.get "/", (req, res) ->
  res.render "index",
    myConditionVariable: true

Upvotes: 0

Related Questions