gpt4 book ai didi

javascript - Handlebars : 2 sources 1 template

转载 作者:行者123 更新时间:2023-11-28 06:30:11 24 4
gpt4 key购买 nike

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

<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;
}
}
}

显然,这并不优雅,而且很难维护。在不详细了解 Discourse 工作原理的情况下,我不知道该告诉你什么。在模板的渲染时,应传递包含所有相关数据的完整对象。对 Handlebars.compile() 的后续调用将需要完整的数据集。也许应该考虑找到一种方法来拆分这些模板并将它们异步呈现为单独的页面元素,或者查看 Partials

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

关于javascript - Handlebars : 2 sources 1 template,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34777201/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com