API / Apache Velocity Interview questions
How do you use the #break directive?
#break exits the innermost enclosing #foreach loop (or a #macro block) immediately, skipping any remaining iterations or statements in that block, similar to break in Java.
#foreach($item in $items) #if($item.id == $targetId) Found: $item.name #break #end #end
It only exits the nearest enclosing loop or macro, not the whole template render — for that, #stop is the correct directive instead. #break was added in Velocity 2.x; older 1.x versions did not support it, and workarounds relied on setting a boolean flag and checking it in the loop's #if condition.
More Related questions...