Skip to content

Instantly share code, notes, and snippets.

@danmalcolm
Created July 7, 2015 12:00
Show Gist options
  • Save danmalcolm/c3c2f84319f009b04688 to your computer and use it in GitHub Desktop.
Save danmalcolm/c3c2f84319f009b04688 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Web.Mvc;
using System.Web.WebPages;
namespace Whatever
{
public static class HtmlHelperExtensions
{
/// <summary>
/// Renders each item in a list using the supplied template, using an HTML comment to avoid whitespace
/// being present between each element.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="items"></param>
/// <param name="template"></param>
/// <returns></returns>
public static HelperResult ElementsWithoutWhitespace<T>(this HtmlHelper html, List<T> items, Func<T, HelperResult> template)
{
const string commentHtml = @"<!-- Inline block fix - don't delete
-->";
return new HelperResult(writer =>
{
int index = 0;
foreach (var item in items)
{
bool last = index == items.Count - 1;
template(item).WriteTo(writer);
if (!last)
{
writer.Write(commentHtml);
}
index++;
}
});
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment