Skip to content

Instantly share code, notes, and snippets.

@samandmoore
Created March 20, 2012 00:20
Show Gist options
  • Save samandmoore/2128896 to your computer and use it in GitHub Desktop.
Save samandmoore/2128896 to your computer and use it in GitHub Desktop.
Render Macros in Umbraco UserControl
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
using System.Web.UI;
using umbraco;
namespace samandmoore
{
public static class UmbracoMacroHelpers
{
public static string RenderMacros(string content, int pageId) {
// load up the current "page" in umbraco speak, sort of like our umbraco request context
var currentPage = new page(((System.Xml.IHasXmlNode)umbraco.library.GetXmlNodeById(pageId.ToString()).Current).GetNode());
if (string.IsNullOrWhiteSpace(content))
return string.Empty;
// First parse for known umbraco tags
// <?UMBRACO_MACRO/> - macros
// <?UMBRACO_GETITEM/> - print item from page, level, or recursive
var regex = new Regex("<\\?UMBRACO_MACRO[^>]*/>|<\\?UMBRACO_GETITEM[^>]*/>|<\\?(?<tagName>[\\S]*)[^>]*/>", RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace);
return regex.Replace(content, tag => {
try {
// parse the attributes from this tag
Hashtable attributes = helper.ReturnAttributes(tag.Value.ToString());
// if the tag is a macro, try to convert it into it's output string
if (tag.ToString().ToLower().IndexOf("umbraco_macro") > -1) {
string macroAlias = helper.FindAttribute(attributes, "macroalias");
if (!string.IsNullOrWhiteSpace(macroAlias)) {
return GetRenderedMacro(macroAlias, currentPage, attributes, pageId);
}
}
return tag.Value;
} catch {
return tag.Value;
}
});
}
public static string GetRenderedMacro(string macroAlias, page umbPage, Hashtable attributes, int pageId) {
var m = macro.ReturnFromAlias(macroAlias);
Control c = m.renderMacro(attributes, umbPage.Elements, pageId);
TextWriter writer = new StringWriter();
var ht = new HtmlTextWriter(writer);
c.RenderControl(ht);
string result = writer.ToString();
return result;
}
public static IEnumerable<macro> ParseMacros(string content) {
// First parse for known umbraco tags
// <?UMBRACO_MACRO/> - macros
// <?UMBRACO_GETITEM/> - print item from page, level, or recursive
MatchCollection tags = Regex.Matches(content, "<\\?UMBRACO_MACRO[^>]*/>|<\\?UMBRACO_GETITEM[^>]*/>|<\\?(?<tagName>[\\S]*)[^>]*/>", RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace);
foreach (Match tag in tags) {
Hashtable attributes = helper.ReturnAttributes(tag.Value.ToString());
if (tag.ToString().ToLower().IndexOf("umbraco_macro") > -1) {
String macroAlias = helper.FindAttribute(attributes, "macroalias");
if (!string.IsNullOrWhiteSpace(macroAlias)) {
yield return macro.ReturnFromAlias(macroAlias);
}
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment