Handlebarsjs检查字符串是否等于值

时间:2015-12-13 15:37:30

标签: string handlebars.js logical-operators

Handlebars是否可以在不注册帮助程序的情况下检查字符串是否等于另一个值?我似乎无法在Handlebars参考文献中找到与此相关的任何内容。

例如:

{{#if sampleString == "This is a string"}}
...do something
{{/if}}

13 个答案:

答案 0 :(得分:29)

看来你不能“直接”做到这一点

尝试使用助手,为什么不呢?

在您的javascript代码中注册帮助:

Handlebars.registerHelper('ifEquals', function(arg1, arg2, options) {
    return (arg1 == arg2) ? options.fn(this) : options.inverse(this);
});

在模板中使用:

{{#ifEquals sampleString "This is a string"}}
    Your HTML here
{{/ifEquals}}

此处有更多详情: Logical operator in a handlebars.js {{#if}} conditional

<强> UPD: 另一种方式:

假设您的数据是:

var data = {
    sampleString: 'This is a string'
};

然后(使用jQuery):

$.extend(data, {isSampleString: function() {
    return this.sampleString ==  'This is a string';}
});

使用模板:

{{#if isSampleString}}
    Your HTML here
{{/if}}

答案 1 :(得分:6)

我只会使用这样的助手:

Handlebars.registerHelper('ifeq', function (a, b, options) {
    if (a == b) { return options.fn(this); }
    return options.inverse(this);
});

Handlebars.registerHelper('ifnoteq', function (a, b, options) {
    if (a != b) { return options.fn(this); }
    return options.inverse(this);
});

然后在您的代码中:

{{#ifeq variable "string"}} 
    ... do this ... 
{{/ifeq}}
{{#ifnoteq variable "string"}} 
    ... do this ... 
{{/ifnoteq}}

答案 2 :(得分:4)

刚从谷歌搜索来看这篇文章如何检查一个字符串是否等于另一个字符串。

我在NodeJS服务器端使用HandlebarsJS,但我也使用HandlebarsJS的浏览器版本在前端使用相同的模板文件来解析它。这意味着如果我想要一个自定义帮助器,我必须在两个不同的位置定义它,或者为相关对象分配一个函数 - 太费力了!

人们忘记的是某些对象具有可以在胡子模板中使用的继承函数。如果是字符串:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match

  

包含整个匹配结果和任何括号捕获的匹配结果的数组;如果没有匹配则为null。

我们可以使用此方法返回匹配数组,如果未找到匹配项,则返回null。这很完美,因为查看HandlebarsJS文档http://handlebarsjs.com/builtin_helpers.html

  

您可以使用if帮助器有条件地渲染块。如果其参数返回false,undefined,null,&#34;&#34;,0或[],Handlebars将不会渲染块。

因此...

{{#if your_string.match "what_youre_looking_for"}} 
String found :)
{{else}}
No match found :(
{{/if}}

更新:

在所有浏览器上测试后,这不适用于Firefox 。 HandlebarsJS将其他参数传递给函数调用,这意味着当调用String.prototype.match时,第二个参数(即上述文档中匹配函数调用的Regexp标志)似乎正在传递。 Firefox认为这是对String.prototype.match的弃用,因此会中断。

解决方法是为String JS对象声明一个新的函数原型,然后使用它:

if(typeof String.includes !== 'function') {
    String.prototype.includes = function(str) {
        if(!(str instanceof RegExp))
            str = new RegExp((str+'').escapeRegExp(),'g');
        return str.test(this);
    }
}

确保在运行Handlebars.compile()函数之前 之前包含此JS代码,然后在模板中

{{#your_string}}
    {{#if (includes "what_youre_looking_for")}} 
        String found :)
    {{else}}
        No match found :(
    {{/if}}
{{/your_string}}

答案 3 :(得分:4)

以前使用匹配的答案对我不起作用,我在 if 语句中遇到错误(类似'必须只有一个参数')。

但是,我刚刚找到解决方案here而无需再编写任何帮助程序:

{{#if (eq person "John")}} hello {{/if}}

答案 4 :(得分:1)

您不能直接比较车把中的字符串,而必须使用帮助器。我在Koa应用程序中尝试了上述解决方案,但无法注册该帮助程序。以下代码为我工作,我认为这也应适用于快速应用程序。我希望这对某人有帮助。

server.js中的代码

var handlebars = require('koa-handlebars');

const isEqualHelperHandlerbar = function(a, b, opts) {
            if (a == b) {
                return opts.fn(this) 
            } else { 
                return opts.inverse(this) 
            } 
        }
        
app.use(handlebars({
    viewsDir: './app/views',
    layoutsDir: './app/views/layouts',
    defaultLayout: 'main',
    helpers : {
        if_equal : isEqualHelperHandlerbar
    }
}));

HBS文件中的代码,其中水果是要比较的变量:

 <select id={{fruit}}>
   <option >Choose...</option>
   <option value="apple" {{#if_equal fruit "apple"}} selected {{/if_equal}}>Apple</option>
   <option value="mango" {{#if_equal fruit "mango"}} selected {{/if_equal}} >Mango</option>
 </select>

答案 5 :(得分:1)

Node.js将此添加到server.js

const isEqual = function(a, b, opts) {
  if (a == b) {
    return opts.fn(this) 
  } else { 
    return opts.inverse(this) 
  } 
}

var hbs = require('hbs');
hbs.registerHelper('if_eq', isEqual);

答案 6 :(得分:0)

Handlebars有一个名为&#39; equal&#39;的条件运算符。这需要两个参数:

1.变量

2.检查变量是否包含的内容。

例如,要检查状态是否为&#39;包含&#39;全职&#39;:

{{#equal status "Full Time"}}  //status is the variable and Full Time is the value your checking for.
    code to be executed
{{else}}
    code to be executed
{{/equal}}

答案 7 :(得分:0)

一个简单的,可重复使用的辅助函数的一个常见情况是,如果值相等则返回string1,如果不相等则返回string2。

示例:

助手(我们称之为“ifEqual”并发送4个参数):

helpers: {

    ifEqual: function (obj, value, trueString, falseString) {
            return ( (obj===value) ? trueString : falseString );
}

模板使用:

对于此示例,假设模板接收具有“transactionType”属性的“transaction”对象:{ transactionType: "expense", description: "Copies" }

假设我们的模板的交易类型为<select>,其中显示了各种<option>s。我们希望使用Handlebars预先选择与transactionType值一致的选项。

我们的新{{ ifEqual }}帮助器用于为<option>插入“已选择”,其匹配值为“费用”。

<select required id="selTransactionType" name="selTransactionType" class="form-control" onchange='transactionTypeChanged()'>
   <option value='hourly' {{ ifEqual transaction.transactionType "hourly" "selected" "" }} >Hourly fee</option>
   <option value='flat' {{ ifEqual transaction.transactionType "flat" "selected" "" }} >Flat fee</option>
   <option value='expense' {{ ifEqual transaction.transactionType "expense" "selected" "" }} >Expense</option>
   <option value='payment' {{ ifEqual transaction.transactionType "payment" "selected" "" }} >Payment</option>
   <option value='credit' {{ ifEqual transaction.transactionType "credit" "selected" "" }} >Credit</option>
   <option value='debit' {{ ifEqual transaction.transactionType "debit" "selected" "" }} >Debit</option>
</select>

答案 8 :(得分:0)

在车把中,括号用于使用(可选)后续项作为参数来调用作为功能列出的第一项。因此,只要您可以自己设置上下文,就可以在没有Ember的情况下使用Ember的语法。例如:

    context.eq = function(param1, param2) {
        return param1 === param2;
    }

    context.notEq = function(param1, param2) {
        return param1 !== param2;
    }

这样做之后,就可以使用标准的{{#if}}和{{#unless}}块操作了:

{{#if (eq someVar "someValue") }}

在使用{{with}}或使用内联部分时切换上下文时要小心。您可能会忘记定义的“ eq”函数。不论新的环境如何,保证的工作方式:

{{#if (@root.eq someVar "someValue") }}

答案 9 :(得分:0)

使用handlebars-helpers,它提供CREATE TABLE Table1 (`id` varchar(1), `loc` int, `status` varchar(7), `date` datetime, `event_time` datetime, `rnk` int) ; INSERT INTO Table1 (`id`, `loc`, `status`, `date`, `event_time`, `rnk`) VALUES ('A', 1, 'READY', '2019-08-04 00:00:00', '2019-08-04 15:39:00', 1), ('A', 1, 'CASTING', '2019-08-04 00:00:00', '2019-08-04 14:09:00', 1), ('A', 1, 'QUEUED', '2019-08-04 00:00:00', '2019-08-04 12:59:00', 1), ('B', 1, 'READY', '2019-08-04 00:00:00', '2019-08-04 23:59:00', 1), ('B', 1, 'CASTING', '2019-08-04 00:00:00', '2019-08-04 13:52:00', 1), ('B', 1, 'QUEUED', '2019-08-04 00:00:00', '2019-08-04 13:44:00', 1), ('C', 1, 'READY', '2019-08-04 00:00:00', '2019-08-04 17:59:00', 1), ('C', 1, 'CASTING', '2019-08-04 00:00:00', '2019-08-04 14:59:00', 1), ('C', 1, 'QUEUED', '2019-08-04 00:00:00', '2019-08-04 11:59:00', 1), ('D', 1, 'READY', '2019-08-04 00:00:00', '2019-08-04 13:59:00', 1), ('D', 1, 'CASTING', '2019-08-04 00:00:00', '2019-08-04 12:59:00', 1), ('D', 1, 'QUEUED', '2019-08-04 00:00:00', '2019-08-04 11:59:00', 1), ('E', 1, 'READY', '2019-08-04 00:00:00', '2019-08-04 21:51:00', 1), ('E', 1, 'CASTING', '2019-08-04 00:00:00', '2019-08-04 18:59:00', 1), ('E', 1, 'QUEUED', '2019-08-04 00:00:00', '2019-08-04 11:59:00', 1) ; 的帮助者

答案 10 :(得分:0)

尝试:

{{#是item.status“完成”}} ... {{/ is}}

答案 11 :(得分:0)

与OP一样,我遇到了同样的困难,因此决定只将调用转租给Javascript,而不是按照我的意愿弯曲把手...

JavaScript函数(在全局范围内)-

function jsIfElse(compare1, compare2, trueResponse, falseResponse) {
  document.write((compare1 == compare2) ? trueResponse : falseResponse);
}

把手片段-

<select multiple id="batter_player_team">
  {{#each teamNamesForFilter}}
  <option value="{{this.id}}">                     <script>jsIfElse('{{this.is_active}}','Y','{{this.name}} *', '{{this.name}}');</script>
  </option>
   {{/each}} 
</select>

答案 12 :(得分:-1)

Mandrill邮件服务支持Handlebars,在这里可以使用“反引号”来评估#if块中的逻辑表达式:

{{#if `operating_system == "OS X"`}}
  <p>Click here for instructions to install on a Mac</p>
{{elseif `operating_system == "Windows"`}}
  <p>Click here for instructions to install on a PC</p>
{{/if}}

我不知道这是否可能,但你应该尝试一下。 这对我来说可以。