javascriptsails.jsejs

How to break a loop with the EJS template language?


I am developping a simple web application with sails.js.

In my frontend code, i'm looping over an array of objects sent by the controller, and i am searching for a specific object. I'd like to break the loop once the object has been found. Is there a clean way to do that using the ejs template language ?

I coulnd't find anything about it on the EJS official website, nor on sails website.

I naively tried this until now :

<% objects.forEach(function(object)  { %>
    <% if(object.someId == someValue) {%>
        <%= object.name %>
        <% break %> <!-- This raise an illegal statement exception -->
    <% } %>
<% } %>

The following code works as expected, but i'm looking for a cleaner solution if any

<% var found = false %>
<% objects.forEach(function(object)  { %>
    <% if(object.someId == someValue && !found) {%>
        <%= object.name %>
        <% found = true %>
    <% } %>
<% } %>

Solution

  • It's not an EJS-related question.

    break statement terminates the current loop. While you are not inside a loop. You are inside callback function, that's called by forEach method once per array element. There's no ability to interrupt forEach (see How to short circuit Array.forEach like calling break?). But, if you need it, you may use for loop for a clean solution:

    <% for (var l = objects.length, i = 0; i < l; i++) { %>
        <% object = objects[i]%>
        <% if(object.someId == someValue) {%>
            <%= object.name %>
            <% break %> <!-- This will work as expected -->
        <% } %>
    <% } %>