Computer Magic Logo
for and foreach loops

Saturday, August 8, 2015

Published by Aristotelis Pitaridis

Let’s see how to use the for loop in a Template using the Razor syntax.

@for (int i = 0; i<5; i++)

As we can see it uses the same approach as we used in the if statement. We add the @ character in front of the for statement and everything works as it is supposed to work. The output of the code will be the following.


We have to mention that the spaces in front of the paragraph tags will appear in the final HTML generated by the Razor engine.

Below there is a similar example for the foreach statement.

@inherits Umbraco.Web.Mvc.UmbracoTemplatePage
    Layout = null;

@foreach (var item in CurrentPage.Children)

The CurrentPage is an object that we will talk about it later. For the moment the only thing that we have to know is that the Children property of the CurrentPage object contains a list of all the child pages that the current page has. We use the foreach statement so that for each child page we will display the name of the page inside a paragraph tag.