Skip to content

Instantly share code, notes, and snippets.

@jmdfm
Created August 24, 2010 16:13
Show Gist options
  • Save jmdfm/547813 to your computer and use it in GitHub Desktop.
Save jmdfm/547813 to your computer and use it in GitHub Desktop.
/// <summary>
/// Helper to avoid the tag soup that comes from rendering Lists of items.
/// Currently supports any number of item detail arguments.
/// <example>
/// Html.RenderList(Model.BoardPosts,
/// "<table><caption>Threads</caption><tbody><tr><th>Thread Name</th><th>Subject</th><th>Posts</th><th>Last Updated</th></tr>{0}</tbody></table>",
/// "<tr><td><a href=\"/Group/ShowForumThread/{3}/{4}\">{0}</a></td><td>{1}</td><td>{2}</td><td>{5}</td></tr>",
/// "<tr><td colspan=\"4\">There are no Threads in this forum yet.</td></tr>",
/// x =>x.Name,
/// x =>x.Subject,
/// x =>x.ChildPosts.Count.ToString(),
/// x =>x.BoardForum.PageName,
/// x =>x.PageName,
/// x => x.UpdatedDate.ToLocalTime().ToString())
/// <remarks>
/// By using the placeholder $index$ anywhere in an item template, the
/// current index in the list will be substituted.
/// </remarks>
/// </example>
/// <param name="list">The list of objects to iterate through.</param>
/// <param name="enclosure">The HTML enclosure to wrap the list in.</param>
/// <param name="itemTemplate">The HTML template to inject the list item details into, using {n} style notation ala string.Format()</param>
/// <param name="empty">The HTML to emit if the list is empty.</param>
/// <param name="actions">The list item details to inject into the HTML item template.</param>
/// <returns>The HTML representing the list.</returns>
/// </summary>
public static string RenderList<T>(this HtmlHelper helper, IEnumerable<T> list,
string enclosure, string itemTemplate, string empty,
params Func<T, string>[] actions) {
try {
return String.Format(enclosure,
(list == null || !actions.Any()
? null
: String.Join(null, list.Select( (i, index) => String.Format(itemTemplate.Replace( "$index$", (index+1).ToString() ),
actions.Select(a => a(i)).Cast<object>().ToArray()))))
?? empty
?? "No items to display");
}
catch (FormatException e) {
throw new FormatException( "Your parameters in the template don't match up with the provided Item details.", e);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment