【问题标题】:Underscore Templating - Partials (with RequireJS)下划线模板 - 部分(使用 RequireJS)
【发布时间】:2012-04-11 14:56:30
【问题描述】:

我正在使用 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>
});

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

【问题讨论】:

    标签: javascript requirejs templating partials underscore.js


    【解决方案1】:

    我想出的解决方案是在模板中实际使用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 }); %>
        <%
    }); %>
    

    【讨论】:

    • 将 javascript 添加到模板会破坏视图的目的。而是使用像 CanJS 这样可以做到这一点的框架:canjs.us/#can_view-render
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-05
    • 1970-01-01
    • 2015-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多