Skip to content

Instantly share code, notes, and snippets.

@rasmuseeg
Created August 25, 2015 12:43
Embed
What would you like to do?
Parsing Macro's inside GridEditors
@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