In canjs, what is the most idiomatic way of conditionally displaying sections of a mustache template based on the existence of any model instances?

129 views Asked by At

I am iterating through each model instance in a mustache style template and want a clean way to show a message if there are no available instances (ex. if someone deletes/destroys them all)

    {{#notifications}}
      <div class='tertiary'>
        <li>Sent {{& displayFrequency frequency}} <br> to <br> <span class='strong'>{{recipients}}</span></li>
        <div id='action-buttons' {{data "notification"}}>    
          <span class='notification-option'><button class='edit'>edit details</button></span>
          <span  class='notification-option'><button class='delete'>delete</button></span>
          <span class='notification-option'>
            <input class="is-active" type="checkbox" {{#if active}}checked{{/if}}>
          </span>
        </div>      
      </div>      
      <br><br>    
    {{/notifications}}

This first way that came to mind:

  {{#if notifications.length}}
    {{#notifications}}
      <div class='tertiary'>
        <li>Sent {{& displayFrequency frequency}} <br> to <br> <span class='strong'>{{recipients}}</span></li>
        <div id='action-buttons' {{data "notification"}}>    
          <span class='notification-option'><button class='edit'>edit details</button></span>
          <span  class='notification-option'><button class='delete'>delete</button></span>
          <span class='notification-option'>
            <input class="is-active" type="checkbox" {{#if active}}checked{{/if}}>
          </span>
        </div>      
      </div>      
      <br><br>    
    {{/notifications}}
  {{else}}
    <div>No Notifications</div>        
  {{/if}}

Are there better ways of doing this? Are there more idiomatic ways of doing this in the context of canjs?

1

There are 1 answers

0
Per Ehnbom On

You can also use the tag #unless to avoid nesting:

{{#each notifications}}
{{/each}}
{{#unless notifications.length}}
{{/unless}}