下划线模板 - 部分(使用 RequireJS)

Underscore Templating - Partials (with RequireJS)

本文关键字:使用 RequireJS 部分 下划线      更新时间:2023-09-26

我正在使用 RequireJS 的tpl!插件将我的模板导入和编译到我的应用程序中 - 类似于text!插件:

define([
    "tpl!../templates/newsfeed.html",
    "tpl!../templates/friends.html",
    "tpl!../templates/tag.html",
    "tpl!../templates/tags.html",
], function (renderNewsfeed, renderFriends, renderTag, renderTags) { … });

这一切都很好用,但我已经到了理想情况下想要使用某种形式的部分的阶段。

目前,如果我想在模板中使用模板,我必须将编译的部分传递给我正在渲染的模板,如下所示:

$('body').append(renderTags({
    tags: tags,
    renderTag: renderTag
}));

然后,在我的模板中:

<section class="tags-list">
    <h1 class="h4 hidden">Tags</h1>
    <% _.each(tags, function (tag) { %>
        <%= renderTag({ tag: tag }) %>
    <% }); %>
</section>

如果我不将编译的部分传递到模板上,那么它将无法找到它。

我的问题是,我怎样才能做得更好?如果我在 RequireJS 定义中定义为依赖项的模板可用于模板本身的变量范围(全局),那么我可能不必将编译的部分传递给模板?

其次,拥有可用于 RequireJS 但用于模板的相同类型的依赖项定义真的很好:

define([
    'tpl!../templates/tag.html'
], function (renderTag) {
    // Obviously this can't be straight HTML, but you get the idea
    <section class="tags-list">
        <h1 class="h4 hidden">Tags</h1>
        <% _.each(tags, function (tag) { %>
            <%= renderTag({ tag: tag }) %>
        <% }); %>
    </section>
});

我可能在一个完全不同的星球上。如果我是,请有人解释一下他们如何使用模板。也许我需要切换模板引擎?

我想

出的解决方案是在模板中实际使用require(),以获取所需的部分,例如:

<%
require([
    "tpl!../templates/partials/tags.html",
    "tpl!../templates/partials/spotify-search.html",
    "tpl!../templates/partials/popup.html"
], function (renderTags, renderSpotifySearch, renderPopup) { %>
    // Template code goes here
    // Partial example:
    <%= renderTags({ tags: tags }); %>
    <%
}); %>