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}}' |
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> |
11 | <p>All lists for current web '{{SP.Site.RootWeb.Title}}' created by the 'splists' tag |
12 |
<ul>{% splists '<li>{0}</li>' %}</ul> |
The screenshot below shows the result of the rendered template sample:
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> |
4 | {% for item in user.tasks -%} |
5 |
<li>{{ item.name }}</li> |
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> |
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> |
7 | Template template = Template.Parse(templateCode); |
9 | string result = template.Render(Hash.FromAnonymousObject( new { |
13 |
Tasks = new List<Task> { |
14 |
new Task { Name = "Documentation" }, |
15 |
new Task { Name = "Code comments" } |
19 | public class User : Drop |
21 |
public string Name { get ; set ; } |
22 |
public List<Task> Tasks { get ; set ; } |
25 | public class Task : Drop |
27 |
public string Name { get ; set ; } |
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 |
3 |
public Dictionary< string , Template> Templates { get ; protected set ; } |
5 |
public TemplateManager() |
7 |
Templates = new Dictionary< string , Template>(); |
10 |
public void AddTemplate( string name, string template) |
12 |
if ( string .IsNullOrEmpty(name)) |
13 |
throw new ArgumentNullException( "name" ); |
14 |
if ( string .IsNullOrEmpty(template)) |
15 |
throw new ArgumentNullException( "template" ); |
17 |
if (Templates.ContainsKey(name)) |
18 |
Templates[name] = Template.Parse(template); |
20 |
Templates.Add(name, Template.Parse(template)); |
23 |
public void RegisterTag<T>( string tagName) where T : Tag, new () |
25 |
Template.RegisterTag<T>(tagName); |
28 |
public void RegisterFilter(Type type) |
30 |
Template.RegisterFilter(type); |
33 |
public string Render( string nameOrTemplate, IDictionary< string , object > values) |
37 |
if (Templates.ContainsKey(nameOrTemplate)) |
38 |
template = Templates[nameOrTemplate]; |
40 |
template = Template.Parse(nameOrTemplate); |
42 |
SharePointDrop sp = new SharePointDrop(); |
46 |
foreach (KeyValuePair< string , object > kvp in values) |
47 |
sp.AddValue(kvp.Key, kvp.Value); |
50 |
return template.Render( new RenderParameters { LocalVariables = |
51 |
Hash.FromAnonymousObject( new { SP = sp }), RethrowErrors = true }); |
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 |
3 |
Dictionary< string , object > _values; |
5 |
public SharePointDrop() |
7 |
_values = new Dictionary< string , object >(); |
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); |
16 |
_values.Add( "Date" , DateTime.Now); |
17 |
_values.Add( "DateISO8601" , |
18 |
SPUtility.CreateISO8601DateTimeFromSystemDateTime(DateTime.Now)); |
23 |
public void AddValue( string name, object value) |
25 |
if ( string .IsNullOrEmpty(name)) |
26 |
throw new ArgumentNullException( "name" ); |
28 |
if (_values.ContainsKey(name)) |
29 |
_values[name] = value; |
31 |
_values.Add(name, value); |
34 |
public override object BeforeMethod( string method) |
36 |
if (! string .IsNullOrEmpty(method) && _values.ContainsKey(method)) |
37 |
return DropHelper.MayConvertToDrop(_values[method]); |
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) |
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); |
16 |
return new SPPropertyDrop(value); |
18 |
return new SPPropertyDrop(value); |
20 |
return new SPPropertyDrop(value); |
22 |
return ((Uri)value).ToString(); |
24 |
return ((Guid)value).ToString( "B" ); |
The SPListItemDrop class for instance is returning the value of the requested field:
1 | internal class SPListItemDrop : SPDropBase |
3 |
public SPListItem ListItem { get { return DropableObject as SPListItem; } } |
5 |
public SPListItemDrop() |
9 |
public SPListItemDrop(SPListItem listItem) |
11 |
DropableObject = listItem; |
14 |
public override object BeforeMethod( string method) |
16 |
if (! string .IsNullOrEmpty(method)) |
18 |
StringBuilder sb = new StringBuilder(); |
19 |
string name = method + "\n" ; |
21 |
for ( int i = 0; i < name.Length; i++) |
27 |
if (name[i + 1] != '_' ) |
41 |
if (ListItem.Fields.ContainsField(name)) |
42 |
return DropHelper.MayConvertToDrop(ListItem[name]); |
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 |
3 |
public static object SPFormatDate( object input) |
5 |
DateTime dt = DateTime.MinValue; |
11 |
dt = SPUtility.ParseDate(SPContext.Current.Web, input as string , |
12 |
SPDateFormat.DateOnly, false ); |
16 |
else if (input is DateTime) |
19 |
if (dt != DateTime.MinValue && dt != DateTime.MaxValue && SPContext.Current != null ) |
20 |
return SPUtility.FormatDate(SPContext.Current.Web, (DateTime)input, |
21 |
SPDateFormat.DateOnly); |
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 |
5 |
public override void Initialize( string tagName, string markup, List< string > tokens) |
7 |
base .Initialize(tagName, markup, tokens); |
9 |
if ( string .IsNullOrEmpty(markup)) |
12 |
_format = markup.Trim().Trim( "\"" .ToCharArray()).Trim( "'" .ToCharArray()); |
15 |
public override void Render(Context context, StreamWriter result) |
17 |
base .Render(context, result); |
19 |
if (SPContext.Current != null && ! string .IsNullOrEmpty(_format)) |
21 |
foreach (SPList list in SPContext.Current.Web.Lists) |
22 |
result.Write( string .Format(_format, list.Title)); |
Download Source Code | Download Article (PDF)