Implement A Generic Template Engine For SharePoint 2010 Using DotLiquid

During the process of creating a complex SharePoint application you often need to send mails and create text files based on SharePoint data elements like SPListItem or SPWeb. Mail templates for instance mostly contain specific list item data. It would be helpful sometimes if the text generation itself is template-driven.

This article shows how to implement a generic template manager based on the free DotLiquid templating system with SharePoint specific extensions. This allows you for example to iterate through all SharePoint lists available within a SiteCollection and render only details for lists which contain Task in their title:

1 <p>All task lists for the current web '{{SP.Web.Title}}' and site '{{SP.Site.Url}}'
2 <ul>
3 {% for list in SP.Lists %}
4 {% if list.Title contains 'Task' %}
5 <li><i>{{list.Title}}</i> with ID '{{Slist.ID|upcase}}' (<i>(Created:
6 {{list.Created|sp_format_date}})</i></li>
7 {% endif %}
8 {% endfor %}
9 </ul>
10 </p>
11 <p>All lists for current web '{{SP.Site.RootWeb.Title}}' created by the 'splists' tag
12 <ul>{% splists '<li>{0}</li>' %}</ul>
13 </p>

The screenshot below shows the result of the rendered template sample:

TemplateEngine

Of course the technique implemented in this article can also be used in conjunction with other technologies or applications, it's not only SharePoint related.

DotLiquid Template Engine

The DotLiquid template engine is a C# port of the Ruby's Liquid templating system and is available for .NET 3.5 and above. DotLiquid is open source and can be downloaded at dotliquidmarkup.org. The software is also available as NuGet package for Visual Studio.

The templating system includes features like variable, text replacement, conditional evaluation and loop statements that are similar to common programming languages. The language elements consists of tags and filter constructs.

The engine can also be easily extended by implementing and adding custom filters and/or tags. This article actually shows how to extend the DotLiquid and implement SharePoint specific parts.

The following sample shows a Liquid template file:

1 <p>{{ user.name | upcase }} has to do:</p>
2
3 <ul>
4 {% for item in user.tasks -%}
5 <li>{{ item.name }}</li>
6 {% endfor -%}
7 </ul>

Output markup is surrounded by curly brackets {{…}} and tag markup by {%…%}. Output markup can take filter definitions like upcase. Filters are simple static methods, where the first parameter is always the output of the left side of the filter and the return value of the filter will be the new left value when the next filter is run. When there are no more filters, the template will receive the resulting string.

There are a big number of standard filters available to use, but later on we will implement a custom filter method for SharePoint. The result of the above rendered template looks like:

1 <p>TIM JONES has to do:</p>
2
3 <ul>
4 <li>Documentation</li>
5 <li>Code comments</li>
6 </ul>

To pass variables and render the template you first need to parse the template and the then just call the Render method with the variable values:

1 string templateCode = @"<ul>
2 {% for item in user.tasks -%}
3 <li>{{ item.name }}</li>
4 {% endfor -%}
5 </ul>";
6
7 Template template = Template.Parse(templateCode);
8
9 string result = template.Render(Hash.FromAnonymousObject(new {
10 user = new User
11 {
12 Name = "Tim Jones",
13 Tasks = new List<Task> {
14 new Task { Name = "Documentation" },
15 new Task { Name = "Code comments" }
16 }
17 }}));
18
19 public class User : Drop
20 {
21 public string Name { get; set; }
22 public List<Task> Tasks { get; set; }
23 }
24
25 public class Task : Drop
26 {
27 public string Name { get; set; }
28 }

The User and Task classes inherit from the Drop class. This is an important class in DotLiquid. The next sections explains the class in more detail. It is out of scope of this article to discuss all the features for DotLiquid in detail. For more information please see the homepage of DotLiquid (dotliquidmarkup.org) or the website of the original creator of the Liquid template language at liquidmarkup.org. You will find there a lot of manuals and sample code.

Template Manager

The TemplateManager class is a wrapper over the DotLiquid template engine and provides SharePoint support. The class allows to cache parsed templates, to register tags and filters and render them using a top-level custom Drop class named SharePointDrop:

1 internal class TemplateManager
2 {
3 public Dictionary<string, Template> Templates { get; protected set; }
4
5 public TemplateManager()
6 {
7 Templates = new Dictionary<string, Template>();
8 }
9
10 public void AddTemplate(string name, string template)
11 {
12 if(string.IsNullOrEmpty(name))
13 throw new ArgumentNullException("name");
14 if(string.IsNullOrEmpty(template))
15 throw new ArgumentNullException("template");
16
17 if(Templates.ContainsKey(name))
18 Templates[name] = Template.Parse(template);
19 else
20 Templates.Add(name, Template.Parse(template));
21 }
22
23 public void RegisterTag<T>(string tagName) where T : Tag, new()
24 {
25 Template.RegisterTag<T>(tagName);
26 }
27
28 public void RegisterFilter(Type type)
29 {
30 Template.RegisterFilter(type);
31 }
32
33 public string Render(string nameOrTemplate, IDictionary<string, object> values)
34 {
35 Template template;
36
37 if(Templates.ContainsKey(nameOrTemplate))
38 template = Templates[nameOrTemplate];
39 else
40 template = Template.Parse(nameOrTemplate);
41
42 SharePointDrop sp = new SharePointDrop();
43
44 if(values != null)
45 {
46 foreach(KeyValuePair<string, object> kvp in values)
47 sp.AddValue(kvp.Key, kvp.Value);
48 }
49
50 return template.Render(new RenderParameters { LocalVariables =
51 Hash.FromAnonymousObject(new { SP = sp }), RethrowErrors = true });
52 }
53 }

The Render method is using the SharePointDrop class to support objects like SPListItem or SPListCollection. The Drop class as key concept of DotLiquid must be explained in detail. The DotLiquid template engine is focusing on making templates safe. A Drop is a class which allows you to export DOM like objects. DotLiquid, by default, only accepts a limited number of types as parameters to the Render method. These data types include the .NET primitive types (integer, float, string, etc.), and some collection types including IDictionary, IList and IIndexable (a custom DotLiquid interface).

If DotLiquid would support arbitrary types, then it could result in properties or methods being unintentionally exposed to template authors. To prevent this, DotLiquid templating system uses Drop classes that use an opt-in approach to exposing object data.

The code following shows the SharePointDrop implementation:

1 internal class SharePointDrop : Drop
2 {
3 Dictionary<string, object> _values;
4
5 public SharePointDrop()
6 {
7 _values = new Dictionary<string, object>();
8
9 if(SPContext.Current != null)
10 _values.Add("Site", SPContext.Current.Site);
11 if(SPContext.Current != null)
12 _values.Add("Web", SPContext.Current.Web);
13 if(SPContext.Current != null)
14 _values.Add("User", SPContext.Current.Web.CurrentUser);
15
16 _values.Add("Date", DateTime.Now);
17 _values.Add("DateISO8601",
18 SPUtility.CreateISO8601DateTimeFromSystemDateTime(DateTime.Now));
19
20 // TODO: Add more default values
21 }
22
23 public void AddValue(string name, object value)
24 {
25 if(string.IsNullOrEmpty(name))
26 throw new ArgumentNullException("name");
27
28 if(_values.ContainsKey(name))
29 _values[name] = value;
30 else
31 _values.Add(name, value);
32 }
33
34 public override object BeforeMethod(string method)
35 {
36 if(!string.IsNullOrEmpty(method) && _values.ContainsKey(method))
37 return DropHelper.MayConvertToDrop(_values[method]);
38
39 return null;
40 }
41 }

The SharePointDrop class main objective is to solve the problem of casting unsupported data types like SPListItem or SPListItemCollection and other SharePoint related types. Therefore the class is overriding the BeforeMethod method of the Drop class to analyse the requested variable value. If the variable is available in the value context the method will try to cast the data type to a known Drop type by calling the MayConvertToDrop method of the DropHelper class:

1 public static object MayConvertToDrop(object value)
2 {
3 if(value != null)
4 {
5 // TODO: Add your own drop implementations here
6
7 if(value is SPList)
8 return new SPPropertyDrop(value);
9 if(value is SPListCollection)
10 return ConvertDropableList<SPPropertyDrop, SPList>(value as ICollection);
11 if(value is SPListItem)
12 return new SPListItemDrop(value as SPListItem);
13 if(value is SPListItemCollection)
14 return ConvertDropableList<SPListItemDrop, SPListItem>(value as ICollection);
15 if(value is SPWeb)
16 return new SPPropertyDrop(value);
17 if(value is SPSite)
18 return new SPPropertyDrop(value);
19 if(value is SPUser)
20 return new SPPropertyDrop(value);
21 if(value is Uri)
22 return ((Uri)value).ToString();
23 if(value is Guid)
24 return ((Guid)value).ToString("B");
25 }
26
27 return value;
28 }

The SPListItemDrop class for instance is returning the value of the requested field:

1 internal class SPListItemDrop : SPDropBase
2 {
3 public SPListItem ListItem { get { return DropableObject as SPListItem; } }
4
5 public SPListItemDrop()
6 {
7 }
8
9 public SPListItemDrop(SPListItem listItem)
10 {
11 DropableObject = listItem;
12 }
13
14 public override object BeforeMethod(string method)
15 {
16 if(!string.IsNullOrEmpty(method))
17 {
18 StringBuilder sb = new StringBuilder();
19 string name = method + "\n";
20
21 for(int i = 0; i < name.Length; i++)
22 {
23 if(name[i] == '\n')
24 continue;
25 if(name[i] == '_')
26 {
27 if(name[i + 1] != '_')
28 sb.Append(' ');
29 else
30 {
31 i++;
32 sb.Append('_');
33 }
34 }
35 else
36 sb.Append(name[i]);
37 }
38
39 name = sb.ToString();
40
41 if(ListItem.Fields.ContainsField(name))
42 return DropHelper.MayConvertToDrop(ListItem[name]);
43 }
44
45 return null;
46 }
47 }

The method parameter (field name of the SPListItem) of the BeforeMethod method can contain underscores which are replaced by spaces. So, field names with spaces like Start Date of the Task item must be defined in the template as {{task.Start_Date}}.

The SPPropertyDrop class, also part of the solution of this article, is a generic Drop implementation which exposes all properties of an object and may cast them if needed into an Drop objects again. For implementation details see the source code.

Filters and Tags

The solution is also providing a custom filter and tag implementation. The filter called sp_format_date (see template above) is implemented by the method SPFormatDate and is calling the FormatDate method of the class SPUtility form the SharePoint API:

1 internal static class SPFilters
2 {
3 public static object SPFormatDate(object input)
4 {
5 DateTime dt = DateTime.MinValue;
6
7 if(input is string)
8 {
9 try
10 {
11 dt = SPUtility.ParseDate(SPContext.Current.Web, input as string,
12 SPDateFormat.DateOnly, false);
13 }
14 catch { }
15 }
16 else if(input is DateTime)
17 dt = (DateTime)input;
18
19 if(dt != DateTime.MinValue && dt != DateTime.MaxValue && SPContext.Current != null)
20 return SPUtility.FormatDate(SPContext.Current.Web, (DateTime)input,
21 SPDateFormat.DateOnly);
22
23 return input;
24 }
25 }

The custom tag named splists is returning a formatted list of all SPList object names of the current web (see template above):

1 internal class SPListsTag : Tag
2 {
3 string _format;
4
5 public override void Initialize(string tagName, string markup, List<string> tokens)
6 {
7 base.Initialize(tagName, markup, tokens);
8
9 if(string.IsNullOrEmpty(markup))
10 _format = "{0}";
11 else
12 _format = markup.Trim().Trim("\"".ToCharArray()).Trim("'".ToCharArray());
13 }
14
15 public override void Render(Context context, StreamWriter result)
16 {
17 base.Render(context, result);
18
19 if(SPContext.Current != null && !string.IsNullOrEmpty(_format))
20 {
21 foreach(SPList list in SPContext.Current.Web.Lists)
22 result.Write(string.Format(_format, list.Title));
23 }
24 }
25 }

Download Source Code | Download Article (PDF)