Skip to content

Instantly share code, notes, and snippets.

@rasmuseeg
Created August 25, 2015 12:43
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save rasmuseeg/a1b3deed488e544ccc62 to your computer and use it in GitHub Desktop.
Save rasmuseeg/a1b3deed488e544ccc62 to your computer and use it in GitHub Desktop.
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