Created
August 25, 2015 12:43
-
-
Save rasmuseeg/a1b3deed488e544ccc62 to your computer and use it in GitHub Desktop.
Parsing Macro's inside GridEditors
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
@using Umbraco.Web.Templates; | |
@using System.Text.RegularExpressions; | |
@using HtmlAgilityPack; | |
@model dynamic | |
<div class="cmscontent"> | |
@Html.Raw(TemplateUtilities.ParseInternalLinks(ParseMacros(Model.value.ToString()))) | |
</div> | |
@functions{ | |
public string ParseMacros(string content) | |
{ | |
var umbracoHelper = new UmbracoHelper(UmbracoContext.Current); | |
var htmlDoc = new HtmlDocument(); | |
htmlDoc.LoadHtml(content); | |
var macroHolders = ( | |
from div in htmlDoc.DocumentNode.Descendants("div") | |
where div.Attributes.Contains("class") | |
&& div.Attributes["class"].Value.Contains("umb-macro-holder") | |
select div | |
).ToList(); | |
foreach(var holder in macroHolders){ | |
// https://regex101.com/r/iG5cZ6/3 | |
string macroHtml = "<" + Regex.Replace(holder.InnerHtml, @"<!-- <\?(UMBRACO_MACRO(.*?))\/> -->", "$1") + "/>"; | |
var macro = HtmlNode.CreateNode(macroHtml); | |
string macroAlias = macro.GetAttributeValue("macroAlias", ""); | |
if (macro != null) { | |
Dictionary<string, object> parameters = ( | |
from attr in macro.Attributes | |
where attr.Name != "macroAlias" | |
select new KeyValuePair<string, object>(attr.Name, attr.Value) | |
).ToDictionary(m => m.Key, m => m.Value); | |
var macroContent = HtmlNode.CreateNode(umbracoHelper.RenderMacro(macroAlias, parameters).ToString()); | |
holder.ParentNode.ReplaceChild(macroContent, holder); | |
} | |
} | |
return htmlDoc.DocumentNode.InnerHtml; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment