繁体   English   中英

把手:2个来源1个模板

[英]Handlebars: 2 sources 1 template

我有一个把手模板,但我想在此模板中包含来自两个不同来源的变量。

<script id="notification-menu-item" type="text/x-handlebars-template">

我试图使两个源都使用相同的模板ID。 这两个文件都有:

var source                 = $("#notification-menu-item").html();
var template               = Handlebars.compile(source);

但是只有来源变量之一进入模板。 无论如何,是否有一个模板可以从两个不同的来源获得其{{variables}}

编辑:代码

这是模板:

<script id="notification-menu-item" type="text/x-handlebars-template">
    <div id="navmenucontainer" class="container">
        <div id="navmenuv">
            <ul class="nav">
              <li>Topics</li>
              <li>Help</li>
              {{#if logged_user}}
                <li>Notifications</li>
                {{#if pro}}
                <li>My Data</li>
                {{/if}}
              {{/if}}
              </ul>
        </div>
    </div>
</script>

pro来自一个.js文件,而logged_user来自一个单独的.js文件。 是否可以在同一模板中使用这两个变量?

如果要在将数据传递到Handlebars.compile()函数之前进行合成,则必须以某种方式将模板的呈现集中到一个函数中。 我猜您将必须以某种方式保证这些“插件” js文件调用此新功能的顺序。 否则,它会变成像这样的东西:

例:

Class1.js

var source = $("#notification-menu-item").html();
var html = Notification.renderNotification(source, logged_user, undefined);
if (typeof html !== 'undefined') {
   $('body').prepend(html);
}

Class2.js

var source = $("#notification-menu-item").html();
var html = Notification.renderNotification(source, undefined, pro);
if (typeof html !== 'undefined') {
   $('body').prepend(html);
}

Notification.js

window.Notification = function() {
   var logged_user = undefined;
   var pro = undefined;
   return {
      renderNotification: function(source, user, isPro) {
         if (typeof user !== 'undefined') {
            logged_user = user;
         }

         if (typeof pro !== 'undefined') {
            pro = isPro;
         }

         if(typeof logged_user !== 'undefined' 
            && typeof pro !== 'undefined') {
               var template = Handlebars.compile(source);
               var html = template({logged_user: logged_user, pro: pro});
               return html;
         }
      }
}

显然,这不是很优雅,而且很难维护。 但是,如果不详细讨论“话语”的工作方式,我不确定该告诉您什么。 在模板渲染时,应传递包含所有相关数据的完整对象。 随后对Handlebars.compile()调用将需要完整的数据集。 也许应该考虑找到一种方法来拆分这些模板,并异步地将它们呈现为单独的页面元素,或者考虑使用Partials

免责声明:我不是JS或无逻辑模板的专家。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM