was hoping for a little help.

What I am trying to achieve is breaking out of an inner loop based on a condition so that i can continue to the outer loop.

Is this possible with underscore.

Something like this.

<% _.each(ApplicationTemplateFields, function(applicationTemplateField){%>
<% _.each(Validations, function(validation){%>
<% if(applicationTemplateField.UniqueKey == validation.UniqueKey) {%>
<div class="form-group has-error">
    <label><%= applicationTemplateField.FieldName %></label>
    <label class="control-label" for="inputError1"><%= validation.ValidationMessage %></label>
    <input type="text" class="form-control inputs" id="inputError1">
</div>
<% break; %>
<%} else {%>
<div class="form-group">
    <label><%= applicationTemplateField.FieldName %></label>
    <input type="text" class="form-control inputs" id="input<%= applicationTemplateField.Id %>">
</div>
<% break; %>
<% } %>
<% }) %>
<% }) %>
有帮助吗?

解决方案

Underscore's documentation for each specifies:

It's also good to note that an each loop cannot be broken out of — to break, use _.find instead.

find will break out as soon as it returns true, so the code would become:

<% _.each(ApplicationTemplateFields, function(applicationTemplateField){%>
<% _.find(Validations, function(validation){%>
<% if(applicationTemplateField.UniqueKey == validation.UniqueKey) {%>
<div class="form-group has-error">
    <label><%= applicationTemplateField.FieldName %></label>
    <label class="control-label" for="inputError1"><%= validation.ValidationMessage %></label>
    <input type="text" class="form-control inputs" id="inputError1">
</div>
<% return true; %>
<%} else {%>
<div class="form-group">
    <label><%= applicationTemplateField.FieldName %></label>
    <input type="text" class="form-control inputs" id="input<%= applicationTemplateField.Id %>">
</div>
<% return true; %>
<% } %>
<% }) %>
<% }) %>

I notice that all the code inside your inner loop is in an if else statement, and either way you want to break. This means your loop will always break on the first iteration, making it largely redundant since only the first item in the collection will be iterated over. If this is intentional, you can avoid the inner loop entirely and simplify the template logic:

<% _.each(ApplicationTemplateFields, function(applicationTemplateField){%>
<% var validation = Validations[ 0 ]; %>
<% if(applicationTemplateField.UniqueKey == validation.UniqueKey) {%>
<div class="form-group has-error">
    <label><%= applicationTemplateField.FieldName %></label>
    <label class="control-label" for="inputError1"><%= validation.ValidationMessage %></label>
    <input type="text" class="form-control inputs" id="inputError1">
</div>
<%} else {%>
<div class="form-group">
    <label><%= applicationTemplateField.FieldName %></label>
    <input type="text" class="form-control inputs" id="input<%= applicationTemplateField.Id %>">
</div>
<% } %>
<% }) %>
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top