【问题标题】:dynamically choose the right template to use动态选择要使用的正确模板
【发布时间】:2013-10-06 19:36:31
【问题描述】:

我正在浏览一个帖子列表,并根据内容类型(图像、文本、推特帖子)选择正确的 html 车把模板。但是,随着越来越多的模板类型,这变得相当难看:

<template name="postItem">

{{#if isType "image"}}
    {{#if isSinglePost}}
        {{>postImageSingle}}
    {{else}}
        {{>postImage}}
    {{/if}}
{{/if}}
{{#if isType "rich"}}
    {{#if isSinglePost}}
        {{>postRichSingle}}
    {{else}}
        {{>postRich}}
    {{/if}}
{{/if}}
{{#if isType "video"}}
    {{#if isSinglePost}}
        {{>postRichSingle}}
    {{else}}
        {{>postRich}}
    {{/if}}
{{/if}}
{{#if isType "file"}}
    {{#if isMimeType "audio/wav"}}
        {{>postAudio}}
    {{else}}
        {{>postFile}}
    {{/if}}
{{/if}}
{{#if isType "link"}}
    {{#if isProviderName this "Twitter"}}
        {{>postTwitter}}
    {{else}}
        {{#if isSinglePost }}
            {{>postLinkSingle}}
        {{else}}
            {{>postLink}}
        {{/if}}
    {{/if}}
{{/if}}

{{#if isType "preview"}}
    {{>postPreview}}
{{/if}}

{{#if isType "photo"}}
    {{>postImage}}
{{/if}}

</template>

将逻辑移到辅助函数中会更好,但我纠结的是如何从辅助函数返回要使用的模板名称。

{{>getTemplateName}}

Template.postItem.getTemplateName = function () {
    return postImage;
};

但这当然给了我:

Exception from Deps recompute: Error: No such template 'getTemplateName'

【问题讨论】:

    标签: meteor handlebars.js


    【解决方案1】:

    {{&gt; template}} 语法仅用于插入模板,而对于助手,您使用 {{helper}},不带尖括号 &gt;。从您的助手调用中删除括号,并在助手中呈现所需的子模板:

    Template.postItem.getTemplateName = function() {
        return new Handlebars.safeString(Template.postImage());
    
    };
    

    【讨论】:

    • 在玩弄了这个建议之后,我认为它需要通过this:return new Handlebars.safeString(Template.postImage(this)) 传递上下文。感谢您帮助我走上正轨。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-15
    • 1970-01-01
    • 2011-04-29
    • 1970-01-01
    相关资源
    最近更新 更多