SharePoint Rendering Templates – The Basics

When I started thinking of blogging on this subject, I thought it would be good to introduce the template based controls in ASP.NET as a starting point and move towards a discussion on how SharePoint uses this technique to provide a host of extension points to itself. Then I decided it better to focus on the SharePoint side of things to keep the article as small as possible. Besides, the basics of the ASP.NET template controls are available within MSDN documentation itself if the reader wishes to learn more about them.

I am still not sure whether the developers at Microsoft wanted these techniques to be available to the wider SharePoint development community – since I can’t seem to find a lot of documentation on this from SharePoint 2007 days, and there is nothing in the latest Visual Studio 2010 SharePoint Development Tools to say that that situation has changed from 2007. Probably the thinking behind there maybe: Is it really necessary since there are web parts, web controls, InfoPath forms, ASP.NET forms to fill the gaps of the requirement of being able to customize the SharePoint UI?

Probably not is the answer, but let us look at a scenario where, I believe, a more “surgical” change would be better: Say we have a requirement to disable all fields in a list / document library edit form if a workflow is active on that item – and also provide a warning to the user that they cannot edit any part of the form until the active workflow is completed. Obviously, we can get this done by creating an ASP.NET form or an InfoPath form and associate it with the library. But the question is whether there isn’t a more localised solution to this than changing the whole form for the list, and how about the argument for keeping the form as close as possible to the out of the box SharePoint list form?

The answer is that there is one and it is good – we use Rendering Templates.

Rendering Templates?

Rendering templates are closely tied to the “templated” controls in ASP.NET. In fact, SharePoint uses that same technique but with a bit of a twist. For those who are new to this technique follow this link to learn more about it.

If you have created custom fields in SharePoint, you might already have used rendering templates. If not the following section provides a quick primer.

When SharePoint requires to render a list form for an item, the following happens:

1) Look at the FormURL XmlDocument definition for the content type related to the item. If found redirect user to that form and pass the relevant information to it. It is up to the form to decide what to do with the data and how it saves the data back to the appropriate list.

2) If no FormUrls are specified, look at the FormTemplates XmlDocument specified for the content type. If specified, the FormTemplate is parsed and presented to the user.

Of the above, we are going to delve deep into the FormTemplate rendering by SharePoint. We will also look at how we can extend and customize this mechanism so we can change the way list forms function for a content type.

Side Note: The reader is probably aware that every content type to exist in the SharePoint space have their parent as one of the built-in content types in the system. This means that by default all lists and libraries have at least one content type enabled with them. For e.g. for a document library, by default, a “Document” content type will be enabled and all items created within it are based on the “Document” content type. When the user adds a field or removes a field, the change is made to the “Document” content type associated with the list. The reader is probably also aware of the fact that “Document” content type associated with a list (The list content type) is not exactly equal to the “Document” content type as was installed with SharePoint (The site content type). This is because the list content type is an instance of the site content type and is different. So making changes to the list content type doesn’t impact the site content type.

We will start by looking at the content type definition for “Item” content type. The “Item” content type is the base content type for all items that belong to a SharePoint list.

The key thing to look for in the above snippet is the “ListForm” value for Display, Edit and New elements within FormTemplates. You can see that “ListForm” is the name of a template defined somewhere in SharePoint that will be used to display all aspects of the form. This also indicates to us that when defining a content type we may specify a different value in those elements to provide a different form to be displayed.

At runtime, when a user clicks on an item in a list or attempts to create a new item or edit an existing item, SharePoint opens the relevant form that lives within the “Forms” sub folder within the List. For e.g. when selecting “New Item” from the ribbon, SharePoint opens the “NewItem.aspx” in a list editor dialog. If we were to open these forms within SharePoint designer, you will see a reference to ListFormWebPart. The magic of loading the appropriate template lives within this web part.

During the initialization phase of the ListFormWebPart, the content type definition is checked for specification of Form Page URLs, if specified the user is redirected to that page. If not the template specified is initialized and rendered on to the page. If no custom template is specified, then the default “ListForm” template is used. Since almost all of the content types derive from this basic Item content type, we can assume that the fall-back template for all forms for all types of items is the ListForm. Studying this form will give us the mechanics of pretty much all types of forms within SharePoint.

Lets look at the templates themselves and see what we have in there. Using Visual Studio open up DefaultTemplates.ascx that lives within the TEMPLATESCONTROLTEMPLATES in the SharePoint Hive. If you look closely, you will see that almost all of the file is comprised of SharePoint:RenderingTemplate tags with different “Id” values specified. If you scroll down to about the middle of the file you will see a rendering template definition with Id set to “ListForm”. This is the form that we were talking about in the previous paragraph. For the readers who have developed User Controls in ASP.NET, the syntax specified is no different from any other regular ASP.NET control definitions.

Within the ListForm template definition, we can find a series of references to various components within the Microsoft.SharePoint.WebControls namespace. If you were to open this namespace within Reflector you will find that ALL of the referenced components derive from a FormComponent control which in turn derives from TemplateBasedControl control.

To understand how it all fits together let us take a look at a fairly simple component that exists within the ListForm template – the CreatedModifiedInfo component. This component is responsible for displaying the values of the Author, Editor, Modified and Created fields of a list item in a human readable format within a ListForm.

The below abstract class diagram explains the general inheritance hierarchy of this component.

Image

At the top of the hierarchy is the TemplateBasedControl, which as the name suggests provides the base implementations for the relevant properties that the runtime can use to instantiate controls derived from it and also has relevant properties that allows a component developer to specify what templates to use for rendering the contents of a control. One of the properties exposes the SPContext related to the item as RenderContext. The FormComponent is the next level in the hierarchy and adds List and Item context related properties into the mix. It uses the RenderContext from the base class to figure out many of the Item and List context related information. This component then becomes the base for all components that has anything to do with a SharePoint list item form. From here on all components that inherit from FormComponent are specialized controls doing specialized things in the form.

The CreatedModifiedInfo Component

We will look at the structure of the CreatedModifiedInfo component in this section. This will give us an idea of how we can structure our own component later on. I have used Reflector to open up the bonnet on the SharePoint assembly and study the inner workings. Most of the code listed here are sections from within this assembly – hence the copyright is held by Microsoft.

The class declaration for the component looks something like below:

The class is sealed so no one can inherit from it. It derives directly from FormComponent as well. The class has an empty constructor that hides the empty constructor from FormComponent. There is no specific reason for it since FormComponent doesn’t do anything within its default constructor.

The class then overrides a slew of properties from the base . The most important one is the DefaultTemplateName property which returns a string with the name of the rendering template to be used by the runtime. What should be noted is that the name MUST match one of the rendering templates by ID, and which is defined within any of the ascx files within the CONTROLTEMPLATES folder in the SharePoint hive. We will get to how SharePoint loads the templates in a later section. The override for this component is not a straightforward return of a string with the template name in it though, as you will see below:

The get property accessor ensures there is no versioning enabled in the list associated with the item and returns a template name by the name of CreatedModifiedInfo. If versioning is enabled, then it returns a different template name. That is a neat trick! Depending on the state of the component, the developer is provided the capability of using a different rendering template, there by altering how the control is displayed on the page. Here you can pretty much guess what the component is doing.

There are other overrides specified, but I will let the reader fiddle around and understand what is happening. We will focus, for now, on just the template side of things.

If we were to search for the CreatedModifiedInfo name within the DefaultTemplates.ascx you will find something along the lines of the below listing:

You may have noticed in the above listing that the template not only contains standard HTML tags, but also references to other controls within the WebControls namespace. What this means is that we are not obliged to just use standard tags, but can put in ANY ASP.NET control to suite our needs. Here the references are more towards other FormComponent based controls. Which means we can nest templates within templates until we are satisfied. Because each of these references are not directly referencing the template names, but ASP.NET controls which in turn references the template by name – we have a very extensible and reusable set of components each performing distinctive functions within where they are used. For an example of this “phenomena” take a look at FieldLabel template which is used in ListFieldIterator template. We will be covering ListFieldIterator in the next part of this series in detail.

The DefaultTemplates.ascx File

You may have noticed multiple references to this file in the above sections. Let us look at how this file is used within SharePoint. This file is loaded, parsed and cached by the runtime somewhere in the initial stages of the application pool start-up. The contents of this file can be described thus:

1) The file contains definitions of pretty much all templates used by various parts of the SharePoint runtime.

2) Each template is defined as SharePoint:RenderingTemplate tag with the ID set to a unique name.

3) Each RenderingTemplate tag contains a “Template” tag which contains HTML tags and references to other controls that make up the layout and functionality pertaining to that template.

4) The format of the file is no different from a normal user control definition in ASP.NET.

The templates defined in this file are loaded and used primarily in forms for a list or a library. There are other places where they are used as well – for e.g. rendering templates for custom field types etc. We will focus on the forms for now since that is the most used and most visible of places where rendering templates are used.

We will use the scenario of a user clicking on “New Item” option on a simple list with a few columns. On a high level the following would be the flow:

1) Open “NewItem.aspx” from the Forms folder of the list in a dialog window.

2) NewItem.aspx contains ListFormWebPart which is initialized.

3) In the OnInit method of the ListFormWebPart the content type of the item is checked to see if there any URLs specified, if so the user is redirected to that URL

4) If no forms are configured, in the CreateChildControls the content type properties are checked for any template specification.

4) Request SPControlTemplateManager for the template by name. The return value is checked to see if a template is available, if so it is rendered, otherwise no rendering takes place.

Let us drill down deeper into each of the above points starting from point 4. Open Reflector again and open Microsoft.SharePoint assembly from the ISAPI folder of the hive. Drill down to the Microsoft.SharePoint.WebPartPages namespace and open the node to see all the classes inside. Find ListFormWebPart in that list and expand it one level. You should see a CreateChildControls method in that list. Right click on it and click on Disassemble. The key part of this method is this section at the bottom which goes something like this:

Ignoring the ControlMode property part above, we see 3 things happening:

1) A Template Container is initialized

2) The template itself is instantiated in the container.

3) The container is then added to the page’s control stack

The template container will be responsible for hosting the template within the control stack. The only difference between the regular container control and the one defined in the SharePoint namespace is that this control is setup to have more SharePoint related properties. Most of these properties are marked internal and are used by the templates themselves to initialize and get data related to the current SharePoint context. The key part of a template container definition is that it implements the INamingContainer interface. The class itself can be derived from a regular control of any kind, like the ASP.NET Panel control. Some additional information on INamingContainer and its place in template based control development can be found in this link.

So how is the template name specified converted to an an object instance? For that we need to drill deeper into the “Template” property referenced above. The below listing is from the Template property definition of the ListFormWebPart

It is quite easy to read through the above listing to understand what is going on. The main line to focus on is line 7. The SPControlTemplateManager is responsible for loading, parsing and caching all rendering templates from ALL ascx files within the root of CONTROLTEMPLATES folder within the SharePoint hive. We will look into the definition of this class in the next article in the series. For now it is sufficient for the reader to know that at the end of executing that line of code, the “template” private variable will hold an instance of the template.

Summary

I think this is a good place to stop for this article. We will look at how it all fits together in the next article in the series where we implement a template and use it with a SharePoint list.

  • Amit Yadav

    its really good article..but can you provide information about the, what are the ids used for customizing mobile pages in SharePoint 2010?

    • Anonymous

      Thanks for the comment. To check the mobile templates, use DefaultMobileTemplates.ascx in the CONTROLTEMPLATES directory.

  • Pingback: » SharePoint Rendering Templates–An Implementation » Of Shared Points()

  • Anna Yafi

    thank you very much ! it’s one of the rare detailed article about all that shareponit mechanism. very clear and precise

    • Anonymous

      Hello Anna,

      Thanks for your comments