【问题标题】:Rendering templates based on session variable基于会话变量渲染模板
【发布时间】:2012-12-06 05:53:33
【问题描述】:

我正在使用 Meteor、Handlebars 和 Backbone 创建一个多页应用程序。我有一个使用主干设置的路由器,它设置了一个会话变量currentPage。如何根据currentPage 的值呈现不同的模板?

有人告诉我,我可以创建一个模板辅助函数来执行此操作,但我不确定如何处理。

【问题讨论】:

    标签: backbone.js meteor handlebars.js


    【解决方案1】:

    如果 currentPage 是全局的并且页面存储为字符串,那么我希望它可以工作:

    Handlebars.registerHelper('currentPageIs',function(page){
        return currentPage == page;
    });
    
    // and in the html:
    {{#if currentPageIs '/posts'}}
        {{> posts}}
    {{else}}
        {{> homepage}}
    {{/if}}
    

    【讨论】:

      【解决方案2】:

      这里有一个非常简单的解决方案:https://gist.github.com/3221138

      但我强烈建议安装meteor-router。这将要求您首先安装meteorite

      另外,要知道官方的路由解决方案在roadmap

      【讨论】:

        【解决方案3】:

        最好的选择是使用 Iron-Router,但你不希望这是一个更改模板的好模式:

        //HTML
        <body>
          {{>mainTemplate}}
        </body>
        
        //JS Client Initially
        var current = Template.initialTemplate;
        var currentDep = new Deps.Dependency;
        
        Template.mainTemplate = function()
        {
          currentDep.depend();
          return current;
        };
        
        function setTemplate( newTemplate )
        {
            current = newTemplate;
            currentDep.changed();
        };
        
        //Later
        setTemplate( Template.someOtherTemplate );
        

        我不知道如何检查路线,但如果可以,那么您可以使用建议的setTemplate 函数来有条件地更改模板。

        【讨论】:

        • 我在 Meteor 0.9.4 中尝试过这个,但它给出了错误:来自 Tracker 重新计算函数的异常:错误:没有这样的模板:mainTemplate
        猜你喜欢
        • 2016-05-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-03-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多