Rendering an Item with a XSLT stored in sitecore or a database.


I work in an environment where getting something like an XSLT file onto a server requires a full QA test cycle of the whole system so I played around with rendering a sitecore item with XSLT stored inside of a sitecore item. I don’t know if I’ll ever do anything with it but here’s a class that allows you to set the path to to a sitecore item that contains a ‘Xsl Transform’ field.

    public class XslItem : XslFile
    {
        protected override void LoadXsl(System.Xml.XmlDocument xsl, string path)
        {
            Item item = Sitecore.Context.Database.GetItem(path);
            if (item != null)
            {
                if (!item.Fields.IsNullOrEmpty("Xsl Transform"))
                {
                    string xslField = item.Fields["Xsl Transform"].GetValue(true);
                    xsl.LoadXml(xslField);
                    return;
                }
            }
            base.LoadXsl(xsl, path);
        }
    }

Then to use it you’ll want something like this :


  XslItem file = new XslItem();
  file.Path = "/sitecore/content/SomeItemWithXslTransformField";
  file.DataSource = "/sitecore/content/theDataItem");
  HtmlTextWriter writer = new HtmlTextWriter(new StringWriter());
  file.RenderControl(writer);
  string htmlOutput = writer.InnerWriter.ToString();
  return new LiteralControl(htmlOutput);

And you can place your XSL inside of sitecore

public class XslItem : XslFile
{
protected override void LoadXsl(System.Xml.XmlDocument xsl, string path)
{
Item item = Sitecore.Context.Database.GetItem(path);
if (item != null)
{
if (!item.Fields.IsNullOrEmpty(“Xsl Transform”))
{
string xslField = item.Fields[“Xsl Transform”].GetValue(true);
xsl.LoadXml(xslField);
return;
}
}
base.LoadXsl(xsl, path);
}
}
Advertisements

About Kevin Buckley
.Net web developer with a lot of experience in CMS. Currently working at Sitecore as Solutions Engineer.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: