handlerbars.js check if list is empty

前端 未结 5 1057
忘了有多久
忘了有多久 2021-01-31 23:50

Is there a way in Handlebars.js templating to check if the collection or list is null or empty, before going and iterating through the list/collection?

// if lis         


        
相关标签:
5条回答
  • 2021-02-01 00:24

    If you want to check if a collection (cursor) is empty or not, the previous answers won't be useful, instead you must use the count() method :

    {{#if items.count}}
        <p>There is {{items.count}} item(s).</p>
    {{else}}
        <p>There is nothing</p>
    {{/if}}
    
    0 讨论(0)
  • 2021-02-01 00:29

    If you have something that you want to display once and only if the array has data, use

    {{#if items.length}}
        //Render
    {{/if}}
    

    .length will return 0 for empty arrays so we have achieved a real falsey value.

    0 讨论(0)
  • 2021-02-01 00:33

    The "each" tag can take an "else" section too. So the simplest form is:

    {{#each items}}
    // render item
    {{else}}
    // render empty
    {{/each}}
    
    0 讨论(0)
  • 2021-02-01 00:34

    For anyone who needs to use an {{#each}} on top of {{#if}} (i.e. an if loop inside a for loop). Is they have three different list of arrays.

    Using a lookup inside a if statement solves the issue for me. As, the above answers did not solve my issue.

    Here is my code,

    {{#each OtherRandomItems}}
    
      {{this}}
    
      {{lookup ../AnotherRandomItems @index}}
    
      {{#if (lookup ../RandomItems @index)}}
      // render items
      {{else}}
      // render empty
      {{/if}}
    
    {{/each}}
    
    0 讨论(0)
  • 2021-02-01 00:46

    Ok it's simpler than I thought:

    {{#if items}}
    // render items
    
    {{#each items}}
    // render item
    {{/each}}
    
    {{else}}
    // render empty
    {{/if}}
    
    0 讨论(0)
提交回复
热议问题