Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Length check in a handlebars.js {{#if}} conditional

Is there a way in handlebars to check the length of a value? Something like this:

{{#if value.length > 20}
...do something
{{else}}
...do something else
{{/if}}
like image 305
Sivakumar Avatar asked Mar 11 '15 04:03

Sivakumar


People also ask

How do I measure my handlebar length?

All you'll need is a tape measure to take an accurate measurement. Place and hold one end of the tape measure on the end of your mountain bike handlebars. Pull the tape along the handlebar towards the other end and take the reading where the handlebar finishes in mm. This measurement is the handlebar width.

How do you compare two values in Handlebars?

{{if}} is used to check whether a field has a value or not, whereas {{compare}} is used to check whether a field has one value or another value. Check out our Handlebars helper reference for more information on handlebars {{compare}}, {{if}}, and other handlebars expressions!

What is helper in Handlebars?

A Handlebars helper call is a simple identifier, followed by zero or more parameters (separated by a space). Each parameter is a Handlebars expression that is evaluated exactly the same way as described above in "Basic Usage": template {{firstname}} {{loud lastname}}

How do you iterate objects in Handlebars?

To iterate over an object with JavaScript and Handlebars. js, we can use the #each keyword. to add the Handlebars script and the template for looping through each entry in data . We use #each this to loop through each array property.


Video Answer


2 Answers

It's not clear what your value is, a string or an array?

If it's an array, you don't need a helper! You can check if the item at length exists:

{{#if items.[20]}}

Here's a working example to display different messages if the user has one item, vs. multiple items:

{{#if items.[1]}}
You have the following items:
{{#each items}}
* {{this}}
{{/each}}
{{else}}
You have one item: {{items.[0]}}
{{/if}}

Try it at http://tryhandlebarsjs.com/ with sample data like

{
  items: ["foo", "bar"]
}

Not needing a helper is very important for using Handlebars in dynamic templates for mail delivery services (Sparkpost, Sendgrid, Mandrill etc.), which don't allow defining helpers (though Sparkpost has a much richer syntax than Sendgrid).

like image 83
Dan Dascalescu Avatar answered Sep 20 '22 11:09

Dan Dascalescu


Create Handlebars helper like below:-

Handlebars.registerHelper('checklength', function (v1, v2, options) {
'use strict';
   if (v1.length>v2) {
     return options.fn(this);
  }
  return options.inverse(this);
});

and use this like:-

      {{#checklength jobTitle 20}}   //jobtitle is property and 20 is length
             <p>Up to 20</p>
      {{else}}
             <p>Less then 20</p>
      {{/checklength}}

Demo

like image 21
Mohit Kumar Avatar answered Sep 18 '22 11:09

Mohit Kumar