1

I am trying to understand how to set for exemple an userbar in my jade layout actualy I have my layout.jade:

doctype 5
html
head
    title= title
    link(rel='stylesheet', href='/stylesheets/style.css')
body
    include userbar
    block content

In my include I only have the variable environment on my current page.

Don't bit me, I'll take an exemple in Symfony2 franmwork :D for exemple if you have this code in your layout

{% render "AcmeBundle:Acme:menu" %}

It will call AcmeController and the menuAction() method regardless the current page

I would like to have the same system: the render in my jade page will call for exemple a requestHandler

exports.userbar = function(req, res){
    var user = 'ant';
    res.render('userbar', { user: user })
};

And now this will render my userbar :) But I don't know how to do it with jade

If I am not clear ask me questions

Thanks :)

4

1 回答 1

3

在您的情况下,您也必须{% render "AcmeBundle:Acme:menu" %}在每个页面中添加它。在快递方面,我认为您更容易完成相同的任务。你在这里有不同的选择。第一种选择是在特定的请求处理程序中使用user中间件,例如

添加一个快速中间件,它只查找用户并设置app.locals属性。app.locals对所有玉文件都可见。比如这个简单的中间件就足够了

var user = function(req, res, next)
{
   var user = db.find(...);
   app.locals({user: user});
   next(); // Do not render the page here, call the next() 
}

然后在您的路由中,使用var user如下:

app.get('/your_desired_url', user, function(req, res) {
    res.render('your_required_jade_file')
});

您可以在任何您想要的请求处理程序中使用此方法;例如,

app.get('/your_desired_url2', user, function(req, res) {
    res.render('your_required_jade_file')
});

app.get('/your_desired_url2', user, function(req, res) {
    res.render('your_required_jade_file')
});

在第二个选项中,您可以将此中间件添加为通用中间件,例如

app.use(function(req, res, next) {
    var user = db.find(...);
    if(user) app.locals({user: user});
    else app.locals({user: null});

    next(); // Do not render the page here, call the next() 
});

在第二种情况下,您的所有请求都通过此函数传递,因此在 .jade 文件中,user变量始终可用。

在您的 .jade 结构中,您可以使用以下内容

layout.jade

!!! 5
html
  head
  body
    include userbar
    block content

例如dashboard.jade

extends ./layout
block content
  // Your dashboard specific content goes here..

我希望这能解决你的问题。

于 2012-11-15T15:49:35.233 回答