How to skip empty string with mustache?

Member

by rollin , in category: Javascript , 2 days ago

How to skip empty string with mustache?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by jasen , a day ago

@rollin 

In order to skip empty strings with Mustache, you can use a simple conditional statement inside your Mustache template. Here's an example:


Let's say you have an array of strings like this:

1
2
3
const data = {
  strings: ['', 'Hello', '', 'World', '']
};


Now, in your Mustache template, you can iterate over the array and only display non-empty strings like this:

1
2
3
4
5
6
7
<ul>
  {{#strings}}
    {{#this}}
      <li>{{.}}</li>
    {{/this}}
  {{/strings}}
</ul>


In this template, the {{#this}} block will only be rendered if the current string {{.}} is not empty.


When you render the template with the data object, the empty strings will be skipped and only the non-empty strings will be displayed in the list.