2016-01-13 50 views
1

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

<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文件。有没有办法让这两个变量在同一个模板中使用?

+0

你能澄清你的意思吗?“只有一个来源的变量通过”?我在您的问题中包含的代码中没有看到您提供模板的位置。我只看到'Handlebars.compile'。 –

+0

您只编译一个模板,而不是调用它,即'template(params)'。需要进一步澄清你想要做什么。 –

+0

@SeanGlover @StevenSchobert:在模板代码中添加以更清楚我在做什么。在一个JS文件中,我有'var html = template({logged_user:logged_user}); $('body')。prepend(html);'在另一个我有'var html = template({pro:pro}); $('body')。prepend(html);' – stevenpslade

回答

0

你必须传递到Handlebars.compile()功能之前模板的渲染,如果你想集中到一个莫名其妙的功能复合的数据。我想你将不得不以某种方式保证这些“插件”js文件调用这个新函数的顺序。否则,它会变成一些真正janky这样的:

例子:

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或无逻辑模板的专家。