Skip to content

Instantly share code, notes, and snippets.

@kgiszewski
Created March 8, 2018 14:01
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kgiszewski/af3847d98912a0e9dac367520485d778 to your computer and use it in GitHub Desktop.
Save kgiszewski/af3847d98912a0e9dac367520485d778 to your computer and use it in GitHub Desktop.
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using Umbraco.Core.Logging;
using Umbraco.Core.Models;
namespace Foo
{
public static class HtmlHelperExtensions
{
public static IHtmlString RenderNestedContentPartials(this HtmlHelper htmlHelper, IEnumerable<IPublishedContent> contentList, string partialPath, ViewDataDictionary viewDataDictionary)
{
if (contentList == null)
{
return new MvcHtmlString("");
}
var sb = new StringBuilder();
foreach (var content in contentList)
{
sb.AppendLine(_renderPartial(htmlHelper, content, partialPath, viewDataDictionary).ToString());
}
return new HtmlString(sb.ToString());
}
private static IHtmlString _renderPartial(HtmlHelper htmlHelper, IPublishedContent content, string partialPath, ViewDataDictionary viewDataDictionary)
{
var context = HttpContext.Current;
if (content == null || context == null)
{
return new HtmlString("");
}
var sb = new StringBuilder();
//default
var pathToPartials = "~/Views/Partials/NestedContent/";
if (!string.IsNullOrEmpty(partialPath))
{
pathToPartials = partialPath;
}
var partial = string.Format("{0}{1}.cshtml", pathToPartials, content.DocumentTypeAlias);
if (System.IO.File.Exists(context.Server.MapPath(partial)))
{
sb.AppendLine(htmlHelper.Partial(partial, content, viewDataDictionary).ToString());
}
else
{
LogHelper.Info<IPublishedContent>(string.Format("The partial for {0} could not be found. Please create a partial with that name or rename your alias.", context.Server.MapPath(partial)));
}
return new HtmlString(sb.ToString());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment