【问题标题】:Is there any way to reference a Handlebars inline partial programmatically?有没有办法以编程方式引用 Handlebars 内联部分?
【发布时间】:2018-09-27 03:10:57
【问题描述】:

考虑下表template.hbs:

<table class="table table-striped table-hover">
    <thead>
        <tr>
            <th>Id</th>
            <th>Name</th>
            <th>Value</th>
        </tr>
    </thead>
    <tbody>
        {{#* inline "testTableRowTemplate"}}
        <tr>
            <td>{{Id}}</td>
            <td>{{Name}}</td>
            <td>{{Value}}</td>
        </tr>
        {{/inline}}
        {{#* inline "testTableEmptyTemplate"}}
        <tr>
            <td colspan="99">There are no rows</td>
        </tr>
        {{/inline}}
        {{#* inline "testTableLoaderTemplate"}}
        <tr>
            <td colspan="99">
                <i class="fa fa-spinner fa-spin fa-3x fa-fw"></i>
                <span class="sr-only">Loading...</span>
            </td>
        </tr>
        {{/inline}}
    </tbody>
</table>

从代码中,我使用 ajax 调用加载此模板并将其编译为 HandlebarsTemplateDelegate,当有新数据可用时,我使用它来动态刷新表。但是,我希望能够只定位一行,所以我需要一个只有“testTableRowTemplate”部分的 HandlebarsTemplateDelegate 才能做到这一点。有没有办法从代码中做到这一点?我在编译主模板后尝试了以下各项,但无法访问部分模板。

var rowPartial = Handlebars.partials["testTableRowTemplate"]; //doesn't work

var rowPartial = Handlebars.compile("{{>testTableRowTemplate}}"); //doesn't work

我希望避免表有多个 .hbs 文件,因此理想情况下我可以在同一个文件中定义可重用的部分。有什么想法吗?

【问题讨论】:

    标签: javascript typescript handlebars.js


    【解决方案1】:

    您似乎无法从代码中引用这些。我的解决方法如下:

    Table.hbs

    您会注意到这里使用了自定义助手registerPartial。这允许我动态注册一个车把助手。

    <table class="table table-striped table-hover">
        <thead>
            <tr>
                <th>Id</th>
                <th>Name</th>
                <th>Value</th>
            </tr>
        </thead>
        <tbody>
            {{#registerPartial "testTableRowTemplate"}}
            <tr>
                <td>{{Id}}</td>
                <td>{{Name}}</td>
                <td>{{Value}}</td>
            </tr>
            {{/registerPartial}}
        </tbody>
    </table>
    

    Page.ts

    在页面级别,我定义了助手registerPartial。需要注意的是,这将被注册到全局 Handlebars 环境中。因此,所有部分名称都必须是唯一的。这可以通过为每个组件(即 Table、List 等)声明 Handlebars 环境来解决,但这超出了我需要的范围。

    Handlebars.registerHelper('registerPartial', (name, options) => Handlebars.registerPartial(name, options.fn));
    

    Table.ts

    在通过 Handlebars.compile(templateContentFromTablehbs) 加载 Table.hbs 模板后,我现在可以通过执行以下操作获得对行部分的编译引用:

    this._rowTemplate = Handlebars.compile(`{{>${this._rowPartialName}}}`);
    

    现在我可以重复使用this._rowTemplate 对表格行进行部分刷新,而无需刷新整个内容。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-28
      • 1970-01-01
      • 2016-03-04
      • 2013-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多