Created
April 11, 2014 18:25
-
-
Save kgiszewski/10489928 to your computer and use it in GitHub Desktop.
Render Umbraco Inline Partial from a RTE Link
This file contains hidden or 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
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Web; | |
using System.Web.Mvc; | |
using System.IO; | |
using Umbraco.Core.Models; | |
using Umbraco.Web; | |
using Umbraco.Core.Logging; | |
using HtmlAgilityPack; | |
namespace v7.Extensions | |
{ | |
public static class Extensions | |
{ | |
public static IHtmlString TransformInlineLinks(this string input, ControllerContext context) | |
{ | |
if (String.IsNullOrWhiteSpace(input)) | |
{ | |
return new HtmlString(input); | |
} | |
var document = new HtmlDocument(); | |
document.LoadHtml(input); | |
var anchors = document.DocumentNode.SelectNodes("//a"); | |
foreach (var link in anchors) | |
{ | |
var href = link.Attributes["href"]; | |
//glossary terms | |
if (href != null && href.Value.Contains("glossary-term")) | |
{ | |
var contentUrlName = href.Value.Split(new string[] { "/" }, StringSplitOptions.RemoveEmptyEntries).Last(); | |
var umbHelper = new UmbracoHelper(UmbracoContext.Current); | |
var content = umbHelper.TypedContent(1071).Children.FirstOrDefault(x => x.UrlName == contentUrlName); | |
var newNodeStr = RenderRazorViewToString(context, "~/Views/Partials/glossary-term.cshtml", content).Trim(); | |
var newNode = HtmlNode.CreateNode("<span class='glossary-wrapper'>" + newNodeStr + "</span>"); | |
link.ParentNode.ReplaceChild(newNode, link); | |
} | |
} | |
return new HtmlString(document.DocumentNode.OuterHtml); | |
} | |
public static string RenderRazorViewToString(ControllerContext context, string viewName, object model) | |
{ | |
context.Controller.ViewData.Model = model; | |
using (var sw = new StringWriter()) | |
{ | |
var viewResult = ViewEngines.Engines.FindPartialView(context, viewName); | |
var viewContext = new ViewContext(context, viewResult.View, new ViewDataDictionary(model), new TempDataDictionary(), sw); | |
viewResult.View.Render(viewContext, sw); | |
return sw.GetStringBuilder().ToString(); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment