句柄为缺少的字段输出null

use*_*481 3 javascript json html-table missing-data handlebars.js

我正在尝试使用把手来格式化从JSON文件接收的数据.我目前的结构类似于:

        <table class="table table-striped">
            <thead>
            <tr>
                <th>Name</th>
                <th>Mark</th>
                <th>Subject</th>
                <th>School</th>
                <th>Birthday</th>
            </tr>
            </thead>
            <tbody>
            {{#each students}}
            <tr>
                <td>{{ this.name }}</td>
                <td>{{ this.mark }}</td>
                <td>{{ this.subject }}</td>
                <td>{{ this.school }}</td>
                <td>{{ this.birthday }}</td>
           </tr>
            {{/each}}
            </tbody>
        </table>
Run Code Online (Sandbox Code Playgroud)

我拥有的JSON文件没有一致的结构,一些学生元素只包含名称(缺少所有其他字段),有些只包含名称和学校.

如果我使用我当前的代码来模拟JSON文件,我将获得一个包含大量空白单元格的表,我想用"null"来编写.

我想也许我应该写一个寄存器,但如果是这样,我该怎么办?

Arj*_*jan 6

Handlebars.js的最新版本支持以下内容来报告所有缺少的帮助器和值,例如{{myName}},{{something.myName}}或者{{myHelper someValue}},不需要花括号内的虚拟助手:

Handlebars.registerHelper('helperMissing', function(/* [args, ] options */) {
    var options = arguments[arguments.length - 1];
    return 'MISSING VALUE: ' + options.name;
});    
Run Code Online (Sandbox Code Playgroud)

(经过2.0.0测试)

虽然这个问题是针对JavaScript的,但对于后代来说,这是Handlebars.java的解决方案 :

final Handlebars handlebars = new Handlebars();

/*
 * By default, Handlebars outputs an empty String for missing values,
 * and throws an exception if a helper is missing. Here, make it never
 * throw an exception, and show a warning in the result text.
 */
handlebars.registerHelperMissing(new Helper<Object>() {
    @Override
    public CharSequence apply(final Object context, final Options options) 
          throws IOException {
       return "MISSING VALUE: " + options.helperName;
    }
});
Run Code Online (Sandbox Code Playgroud)

(使用最新版本测试,为1.3.2)

对于Mustache.java也是如此:

final DefaultMustacheFactory mf = new DefaultMustacheFactory();

mf.setObjectHandler(new ReflectionObjectHandler() {
    @Override
    public Wrapper find(final String name, final Object[] scopes) {
        Wrapper wrapper = super.find(name, scopes);
        if (wrapper instanceof MissingWrapper) {
            return new Wrapper() {
                @Override
                public Object call(Object[] scopes) throws GuardException {
                    return "MISSING VALUE: " + name;
                }
            };
        }
        return wrapper;
    }
});
Run Code Online (Sandbox Code Playgroud)

(测试版本为0.8.2,有点过时.未使用条件和循环进行测试.)