nodejs jade conditional extend

2019-02-12 16:52发布

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

4条回答
欢心
2楼-- · 2019-02-12 17:18

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
查看更多
叛逆
3楼-- · 2019-02-12 17:22

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

查看更多
一夜七次
4楼-- · 2019-02-12 17:26

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.
查看更多
干净又极端
5楼-- · 2019-02-12 17:32

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!

查看更多
登录 后发表回答