Handlebars.js - Show data only if {{ image_url }} doesn't contain "questionmark"


#1

Hi,

As you can see in this example, which I created on Codepen, some of the data don’t have an image and whenever there’s no image, a place holder image is shown:

Handlebars.js Example

Is there any way in Handlebars.js to say that show the data only if the {{ image_url }} doesn’t contain “questionmark”?

Something similar to this?

{{#each this}}
{{#if image_url !contains "questionmark"}}

    <li class='list-container'>
      <div class="image-container">
          <img src="{{ image_url }}">
      </div>
      <div class="name-container">
        {{ name }}
      </div>
      <div class='role-container'>{{{ role }}}</div>
    </li>

{{/if}}
{{/each}}

#2

I don’t think handlebars allows anything beyond checking value/existence of variables in if template blocks.

If you want to do more complicated things, you’ll generally want to do that in the template data before you run it through the template. In your case, do the “questionmark” check in JavaScript, then put that result in your template data as something like data.noQuestionMark. Then in the template use

{{#if noQuestionMark}}
...

#3

I couldn’t find any solution with Handlebars.js, so I fixed it via pure JS:

(function removeNoImage() {
  for(let key in data.staff) {
    if(data.staff[key].image_url.indexOf('questionmark') !== -1) {
      delete data.staff[key];
    }
  }
})();