Skip to content

Instantly share code, notes, and snippets.

@jwmcpeak
Created March 28, 2011 16:26
Show Gist options
  • Save jwmcpeak/890773 to your computer and use it in GitHub Desktop.
Save jwmcpeak/890773 to your computer and use it in GitHub Desktop.
A quick and easy repeater for Razor.
public static class RazorExtensions
{
// a quick and simple repeater helper method
// header and footer templates could be added
public static HelperResult Repeater<T>(
this IEnumerable<T> items,
Func<T, HelperResult> itemTemplate,
Func<T, HelperResult> alternatingItemTemplate = null,
Func<T, HelperResult> separatorTemplate = null)
{
return new HelperResult(writer =>
{
if (items.Count() > 0)
{
var last = items.Last();
int i = 0;
foreach (var item in items)
{
var func = (i % 2 != 0 && alternatingItemTemplate != null) ? alternatingItemTemplate : itemTemplate;
func(item).WriteTo(writer);
if (separatorTemplate != null && !item.Equals(last))
{
separatorTemplate(item).WriteTo(writer);
}
i++;
}
}
});
}
}
// Usage
@{
var names = new string[] { "Jeremy", "Jason", "Jeffrey", "John", "Jethro" };
}
@names.Repeater(@<p class="classOne">@item</p>, alternatingItemTemplate: @<p class="classTwo">@item</p>, separatorTemplate: @<hr />)
@jwmcpeak
Copy link
Author

jwmcpeak commented Nov 3, 2011 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment