Created
March 28, 2011 16:26
-
-
Save jwmcpeak/890773 to your computer and use it in GitHub Desktop.
A quick and easy repeater for Razor.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 />) |
Howdy, artcarrion. This is a helper method, so it needs to be defined
within a public/internal static class. See
http://msdn.microsoft.com/en-us/library/bb383977.aspx for info on extension
methods.
On Mon, Oct 17, 2011 at 10:55 AM, artcarrion < ***@***.***>wrote:
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<T> 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.
##
Reply to this email directly or view it on GitHub:
https://gist.github.com/890773
##
##
Jeremy McPeak
Author, Professional Ajax 2nd Edition (http://amzn.to/9DgecT)
Author, Beginning JavaScript 4rd Edition (http://amzn.to/9Dvjud)
.NET and JavaScript Reviewer, CodeCanyon
http://codecanyon.net
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.