Skip to content

Instantly share code, notes, and snippets.

@jwmcpeak
Created March 28, 2011 16:26
Show Gist options
  • Select an option

  • Save jwmcpeak/890773 to your computer and use it in GitHub Desktop.

Select an option

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 />)
@artcarrion

Copy link
Copy Markdown

Hello jwmcpeak
It seems the best implementation I've ever seen but I can't make it work because I don't know where I have to put the public class Helperresult Repeater in my MVC3 project. I put it inside one of the controllers I have, but when I try to use it from a view, it doesn't recognize .Repeater method of @NAMEs var.
Could you help me please?
Thanks.

@jwmcpeak

jwmcpeak commented Nov 3, 2011 via email

Copy link
Copy Markdown
Author

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