Search code examples
derbyjs

How to use indexof on array derbyjs


I have an array passed to my template and I want to see if I have the value stored in it:

{{each _page.friends as #friend}}
    {{if _page.user.friends.indexOf(#friend.id)<0}}
        <button>Add</button>
    {{else}}
        Already Friends
    {{/if}}
{{/each}}

Apparently indexOf isn't a function, but the array (_page.user.friends) does seem to exist I can use it its own {{each}}....

Is there a way to do this? Or perhaps a better way?


Solution

  • I do not see support for indexOf mentioned in Derby View documentation. However, you can always use a view function to determine whether someone is a friend or not.

    // in the view
    {{each _page.friends as #friend}}
      {{if isFriend(_page.user.friends, #friend.id)}}
         <button>Add</button>
      {{else}}
        Already Friends
      {{/if}}
    {{/each}}
    
    // in controller
    FriendListController.prototype.isFriend = function(friends, friendId) {
      return friends.indexOf(friendId) > 0;
    };