27. maj 2009 by Kasper B
The topic of the previous post was inline xsl in umbraco
master templates.
Another way to circumvent the macro placeholder for those
transformations that are only used in templates (main navigations
and stuff) - is to create a component that allows you the input
the path of a xsl file - load it up and do the
transformation.
Candidates for this is xsl files wrapped in macros that do not
have a tick in the "Use in editor" field - the gain should be a
"simpler" umbraco installation - and a more transparent development
process - and no more need to look in the macro section with the
sole purpose to find out which xsl file it has a reference to
:).
Prototype code that does the job is done in 67 lines - including
debug code, import and namespace declarations.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using System.Xml.Xsl;
using System.IO;
namespace InlineXsl
{
[ToolboxData("<{0}:XslFile runat=server></{0}:XslFile>")]
public class XslFile : Literal
{
private string _xslpath = "";
public string XslPath {
get { return _xslpath; }
set { _xslpath = value; }
}
private bool _debugmode = false;
public bool DebugMode
{
get { return _debugmode; }
set { _debugmode = true; }
}
protected override void Render(HtmlTextWriter writer)
{
try
{
XmlDocument xd = new XmlDocument();
xd.Load(HttpContext.Current.Server.MapPath(XslPath));
XslCompiledTransform xslt = new XslCompiledTransform();
xslt.Load(xd);
XsltArgumentList xslArg = umbraco.macro.AddMacroXsltExtensions();
xslArg.AddExtensionObject("urn:umbraco.library", new umbraco.library());
xslArg.AddParam("currentPage", "", umbraco.library.GetXmlNodeCurrent().Current);
xslt.Transform(umbraco.library.GetXmlAll().Current, xslArg, writer);
}
catch (Exception ex)
{
if (DebugMode)
{
writer.Write("<div style='color:red;border:1px solid red;padding:10px;'>Error in xsl: <br /><pre>" + ex.ToString() + "</pre></div>");
}
else
{
try
{
HttpContext.Current.Trace.Warn("Error in inline xsl", ex.ToString());
}
catch { }
}
}
}
}
}
When using it in templates it looks like this:
<Inline:XslFile XslPath="/xslt/test.xslt" runat="server" />
Is it something worth adding to the Umbraco project?