使用车把的登录状态相关菜单.js

Login state dependent menu using handlebars.js

本文关键字:菜单 js 状态 登录      更新时间:2023-09-26

我正在尝试应用以下逻辑:

var LoggedOutMenuView = Parse.View.extend({
    template: Handlebars.compile($('#menu-logged-out-tpl').html()),
    render: function(){
        this.$el.html(this.template());
    }
});
var LoggedInMenuView = Parse.View.extend({
    template: Handlebars.compile($('#menu-logged-in-tpl').html()),
    render: function(){
        this.$el.html(this.template());
    }
});
var currentUser = Parse.User.current();
if (currentUser) {
    var loggedInMenuView = new LoggedInMenuView();
    loggedInMenuView.render();
    $('.navbar-fixed').html(loggedInMenuView.el);
} else {
    var loggedOutMenuView = new LoggedOutMenuView();
    loggedOutMenuView.render();
    $('.navbar-fixed').html(loggedOutMenuView.el);
}

。自:

BlogApp.Views.Categories = Parse.View.extend({
    className: 'sidebar-module',
    template: Handlebars.compile($('#menu-logged-out-tpl').html()),
    render: function() {
        var collection = { category: this.collection.toJSON() };
        this.$el.html(this.template(collection));
    }
});

就目前而言,在上面的第二个代码块中,我目前只渲染 #menu 登录的 tpl,但我想像以前一样以用户是否登录为条件。

为什么我不能执行以下操作,我应该怎么做?

BlogApp.Views.Categories = Parse.View.extend({
    className: 'sidebar-module',
    var currentUser = Parse.User.current();
    if (currentUser) {
        template: Handlebars.compile($('#menu-logged-in-tpl').html()),
    } else {
        template: Handlebars.compile($('#menu-logged-out-tpl').html()),
    }
    render: function() {
        var collection = { category: this.collection.toJSON() };
        this.$el.html(this.template(collection));
    }
});

因为您在对象中使用if,所以无法执行此操作。使用条件运算符分配模板值。

BlogApp.Views.Categories = Parse.View.extend({
    className: 'sidebar-module',
    template: Handlebars.compile(Parse.User.current() ? $('#menu-logged-in-tpl').html() : $('#menu-logged-out-tpl').html()),
    render: function() {
        var collection = {
            category: this.collection.toJSON()
        };
        this.$el.html(this.template(collection));
    }
});