手柄中的条件部分

Dan*_*Dan 4 javascript templates handlebars.js ember.js

我有以下数据,我试图提供给Handlebar模板

{
    "set-group": [
        {
            "label": "Source Data",
            "type": "select",
            "options": [
                {
                    "value": "Default Selections"
                },
                {
                    "value": "Other Selections"
                }
            ]
        },
        {
            "label": "Scale",
            "type": "radio",
            "options": [
                {
                    "value": "log",
                    "label": "Log",
                    "groupname": "group2"
                },
                {
                    "value": "linear",
                    "label": "Linear",
                    "groupname": "group2"
                }
            ]
        }
    ]
}
Run Code Online (Sandbox Code Playgroud)

我创建并注册了2个Partials,一个模板"选择"表单元素,另一个模板"无线电"输入.我不知道数据中将包含什么类型的表单元素,因此我需要某种帮助程序来检查type == select并为select选择适当的部分.我在创建这样的帮助器时遇到了麻烦.

我在考虑将数据中的type = select替换为select = true,并使用if/else帮助程序检查true/false但我宁愿保持格式标准化

有任何想法吗?

Dan*_*Dan 13

我最终使用了这个助手

// Comparison Helper for handlebars.js
// Pass in two values that you want and specify what the operator should be
// e.g. {{#compare val1 val2 operator="=="}}{{/compare}}

Handlebars.registerHelper('compare', function(lvalue, rvalue, options) {

    if (arguments.length < 3)
        throw new Error("Handlerbars Helper 'compare' needs 2 parameters");

    operator = options.hash.operator || "==";

    var operators = {
        '==':       function(l,r) { return l == r; },
        '===':      function(l,r) { return l === r; },
        '!=':       function(l,r) { return l != r; },
        '<':        function(l,r) { return l < r; },
        '>':        function(l,r) { return l > r; },
        '<=':       function(l,r) { return l <= r; },
        '>=':       function(l,r) { return l >= r; },
        'typeof':   function(l,r) { return typeof l == r; }
    }

    if (!operators[operator])
        throw new Error("Handlerbars Helper 'compare' doesn't know the operator "+operator);

    var result = operators[operator](lvalue,rvalue);

    if( result ) {
        return options.fn(this);
    } else {
        return options.inverse(this);
    }
  });
Run Code Online (Sandbox Code Playgroud)

资料来源:http://doginthehat.com.au/2012/02/comparison-block-helper-for-handlebars-templates/