Accessing res.locals from Backbone.Router templates

本小妞迷上赌 提交于 2020-01-15 23:07:18

问题


I've been working on a very basic nodejs problem for way too long at this point and I'm stuck. Others have asked similar questions but for some reason the answers don't seem to work for me.

Background:

I'm just ramping up with NodeJS with Express, Backbone, & Passport for auth. Passport stores the user object in the request so I'm trying to pass it up to my Backbone views.

I've been using the Node Cellar project as a starting point and have followed their lead in displaying most of my views via Backbone.Router.extend.

What I'm trying to do:

I just want to pass the user object to a view and display, e.g. a name in my template.

What I've tried:

I'm using middleware similar to the below to pass my user to the model

app.use(function(req, res, next){
   res.locals.user = req.user;
   next();
});

When I use app.get directly I'm able to confirm that this works:

app.get('/test',function index(req, res) {
    res.send(res.locals.user);
});

However, if I include the following in my HeaderView.html file everything breaks down (even if I can confirm user is defined via app.get):

<%= user === null ? "No user" : user %> (or user.name.familyName, etc.)

I get the following error in the console:

Uncaught ReferenceError: user is not defined

Here's what my main.js looks like:

var AppRouter = Backbone.Router.extend({
    routes: {
        "home"               : "home"  
    },

initialize: function () {
    this.headerView = new HeaderView();
    $('.header').html(this.headerView.el);

    var footerView = new FooterView();
    $('#footer').html(footerView.el);
},

home: function (id) {
    if (!this.homeView) {
        this.homeView = new HomeView();
    }
    $('#content').html(this.homeView.el);
},

});

utils.loadTemplate(['HomeView'], function() {
    app = new AppRouter();
    Backbone.history.start();
});

Here's how I'm setting up express:

app.set('port', process.env.PORT || 3000);
app.use(express.logger('default'));  /* 'default', 'short', 'tiny', 'dev' */
app.use(express.bodyParser()),
app.use(express.static(path.join(config.root, 'public')));
app.use(express.cookieParser('optional secret string'));
app.use(express.session({ secret: 'my secret secret key' }));
app.use(passport.initialize());
app.use(passport.session());

Any thoughts?


回答1:


I withdraw my preview answer, as it was shortsighted :)

It looks like you can find your answer here: ExpressJS 3.0 How to pass res.locals to a jade view?

hth,
Aaron



来源:https://stackoverflow.com/questions/19150826/accessing-res-locals-from-backbone-router-templates

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!