Saturday, November 30, 2013

Working with Page Templates

While keeping your Sitecore solution flexible

This blog post is part 4 in a series on “Creating good Sitecore solutions”. Rather than constantly going back and adding edits to the previous posts, just follow this link to get an overview of the series.

The story so far

By following the recommendations I’ve presented in this series, you’ll find yourself building a site that has little or no reliance at all on Page Templates. For starters, this is a good thing. Don’t worry about it.

By doing so, your solution stays on top of the Sitecore feature set – it can be personalised, conditional renderings can be swapped in and out and your marketing users can select winners of M/V tests and go about their business – just like intended. As I’ve argued earlier, the reason you are building this site in Sitecore at all over say… some of the competition… would be because of the distinguishing features of Sitecore. Not for the ability to build websites in Sitecore – I’m reasonably sure this can be accomplished in most competing CMS systems – but because Sitecore offers this great suite of tools surrounding it. The Sitecore Customer Engagement Platform or CEP.

Enabling your solution for these tools really comes down to this:

  1. Individual components on your site must respond to changing Datasource settings (configured by marketers, controlled by Sitecore)
  2. In the extreme, you as a developer really have no real say at all in what components end up on any given page. Marketers can, will and should perform testing of various component combinations on any given page and select winners accordingly. Sure, you can restrict this to some extent – but why should and would you?

All of which is fine, as long as you’ve implemented your components following the principles from this series of posts.

What then, do we use Page Templates for?

Having come this far, it’s probably time to take a look at what Page Templates then really should be, and how they can be used to make not only your life easier, but also that of your marketing users.

The first and most obvious thing that belong on your Page Templates, is “everything that isn’t really part of any component on your page”. Depending on how far your take your components, this could be things like:

  • Page description and keywords – for Google (if you still use these)
  • NOINDEX, NOFOLLOW checkboxes
  • Page titles (browser title, menu title and so on)
  • Page theme
  • Canonical URLs

In essence, anything that you would reasonably output as part of your Layout and Layout code. Data you will be pulling, at runtime, from Sitecore.Context.Item and where the concept of a Datasource makes no sense at all.

Fields like these, I tend to bundle up on a base template I name “Page” (appropriately), and all further Page Templates I implement will be inheriting from this. 

And what else?

You’re not going to like this answer. “It depends”. From this point on, what you choose to implement as Page Templates is up to you. I can tell you a few considerations you should have when deciding, and a few of the trade-offs you’ll be making however.

  • Are your marketing users accustomed to working with Sitecore?  And if they are, have they primarily worked with “traditional” Sitecore implementations, where pretty much all content sat on just one single item (a Page Template) in the Sitecore Content Editor?
    • If so, you should probably cook up a series of Page Templates for them. Fortunately, creating and altering Page Templates is now a much simpler task than it would have been otherwise, if you’ve followed the principles in this series of posts. I’ll demonstrate shortly.
  • Are there areas you are absolutely sure will not be subject of M/V testing?
    • I can tell you this; pretty much EVERY single time I’ve made a “judgment call” on this, I’ve been wrong. Sooner or later, once the marketing users really get into the spirit of really using Sitecore and working with their site, they will be wanting to M/V test the “strangest” things (and they should). All of these from real life, by the way.
      • The ordering of the main navigation menu
      • The naming for the “My Account” area
      • Placing the “left navigation” on the left and right side of the layout
      • Backdrop images for the site
      • “Sign in” versus “Log in” button text
    • Truth is, if your marketing users follow the spirit of continuously testing the site to improve conversion rate (and why wouldn’t they?) – every component is a candidate for testing
  • What about content pages that your marketing users create often?
    • Indeed the traditional candidate for Page Templates, and you probably should set up Insert Options for these
    • However keep in mind that the concept of Layout Presets. You could in reality just give your marketing users a set of insert options that all are simple inheritances of the “Page” template, with different presentation details on them or – alternatively - different Layout Presets
  • Large volumes of “page” items
    • Like an article repository or some such. Yes, you definitely should base these on a common Page Template. But that’s not the same as saying, you should necessarily have a tonne of fields on that template; you’re doing it primarily to have a single place to globally change Presentation Details for these pages.

What I’m getting at is this. Most of the reasons that I – and I suspect many – Sitecore consultants have set up Page Templates in the past, really came down to ease of managing Presentation Details for a given page type. So we’d have a lot of content in the solution, say 1000s of “News Article” items for instance. And then along comes a marketer, wanting to show the “Spring Sale” banner on the top of all of them. No problem; find the “News Article” template, edit the Standard Values Presentation Details for the template and you’re done.

The less common scenario – but quite challenging if you’re following the “old ways” would be; marketing user comes along and wants to replace “Component XYZ” on the “News Article” pages with “Component ZYX”. The two components are not alike in any way, and use completely different fields.

Sure, part of the challenge is easy enough. You go to the “News Article” template Standard Values, you swap the components around. But what then? Do you then change the inheritance of “News Article” so it includes the fields required by “Component ZYX”?   You would have to, unless it was implemented following the principles of these posts – always respecting it’s Datasource, and being based on a known Datasource Template. If it doesn’t, you’re out of luck.

So you proceed and change the inheritance of “News Article” – you put in some default values on the Standard Values item for the template. The rest… well that’s up to the marketing users. There’s 2 problems left lingering here:

  • What about the fields being used by “Component XYZ”?  If you’re lucky, you know exactly what they are and you can proceed to remove them from the “News Article” template. Let’s just hope the fields are not being used by other components on the page
  • Your marketing users can’t edit Standard Values. If the default values you configured need to change, they would need to come to you to get them changed – alternatively manually edit the 1000s of pages (and this, they won’t be happy about)
  • Ok so there’s 3 problems. What if “Component ZYX” really needed a different set of values based on where in the content hierarchy the News Article resided?

No matter your approach, none of this is truly ideal. Having fields on Page Templates is a compromise in pretty much any way you look at it. Both in terms of flexibility and what you can do with the site, but also how you make changes to it going forward.

But if you really want to, here’s how easy it is to make and amend Page Templates following these principles

Having said all of the above, you will still be doing Page Templates. Especially if you’re dealing with marketing users who’ve never known Sitecore to be anything else than the Sitecore Content Editor interface, never did an M/V test in their life and don’t plan to. My own opinions aside; these absolutely do exist. Cater for their current needs, but don’t bar them from moving forward using Sitecore.

Fortunately, this is now easier than ever. Say I have a page like this.

30-11-2013 12-53-13

As shown in my previous posts in this series, this just sits on a very basic “Page” template with no fields on it. All of the components are implemented following these practices, they respect the Datasource given and will fall back to Sitecore.Context.Item if no Datasource is provided for them.

Presentation details for this item looks like this:

30-11-2013 12-56-03

And here’s the item as shown in Sitecore Content Editor

30-11-2013 12-57-36

Let’s then say that I want to make some of the components part of the template for this page. Header and the Top Menu. No problem at all, I go to the Site Root template I’ve set up for this page. This becomes even easier if you have a snapshot of your presentation details showing on the screen.

30-11-2013 13-02-19

The icons you’ve configured for your Datasource Templates help you here. Having done this change, my Home item now looks like this.

30-11-2013 13-04-43

So far, nothing has changed on my site. The presentation details for my components on this page still point to the Datasources I have configured. To change this, I need to then go to my Standard Values for the Site Root, and clear these fields. While I’m there, I set up fill in some Standard Values content on my new fields.

30-11-2013 13-08-25

I clear the Datasources for the components I’m now making part of my Page Template

30-11-2013 13-09-33

And after a quick publish, the site now looks like this.

30-11-2013 13-14-10

For all intents and purposes, my Home item now looks and acts like it was created using traditional “Page Templates”, but I retain the confidence that I can make amendments to this structure easily. The components can still be tested and swapped around and so on – but my marketing users can still keep using the Sitecore Content Editor to work with my “Page”.

For those of you who read my previous post in detail, I would actually normally
choose the DatasourceOrSiteRoot strategy for things such as
the Header component, but that’s not really relevant in the context of this post.

You can, of course, add as many base templates to your Page Template as you desire – for a full blown “Sitecore Content Editor” experience. Remember I said in a previous post; you’re not really building designing your information architecture in the manner I lay out in these posts only to cater for the Page Editor users?  Well this is it – you do it for your Content Editor users as well. And your solution will be better off for it, for both types of users.

And you’ve still not incurred any cost!

I stand on my argument made in previous posts; building up your information architecture in this manner from ground up adds no cost to your implementation.

And I can honestly say, making and amending Page Templates has never been easier. Making them becomes as easy as just identifying which components on the page you consider to be “always part of the page” (and disregarding what I said above; in reality you risk making the wrong judgment call on this) – and make your Page Template inherit from the respective Datasource Template templates.

By doing this; everything still works “as before”. But you now have the certainty (because you’re components are done right) that you can make amendments to this decision in the future. And yes, everything on the page can still be personalised and tested(!). Yes it really can; setting up a test is as simple as defining the test variations (this, your marketing users would need to do in any event) – and setting them up. Default would just be the blank Datasource.

M/V testing when using Page Templates

Set up the variations. I suggest creating a folder with a meaningful name, so you can later do a bit of cleanup and get rid of the losing variations.

30-11-2013 13-46-51

Set up the test, as you normally would.

30-11-2013 13-49-53

And you’re good to go. Your problem only comes, when a winner is selected. This problem is inherent to Page Templates. Consider this:

The test runs, and ultimately the marketing user will select Variation B as the winner. What Sitecore will do is this; it will change the presentation details – so that the Datasource for the Header component gets set to Variation B. And this is fine – if your component is done right, the site will now be showing Variation B whenever rendering the Header component.

Only problem is; you’re still stuck with fields on your Page Template that now no longer hold any meaning. The Header fields on your Page Template are not being used and only act to confuse your marketing users. At least the ones who use the Sitecore Content Editor; in Page Editor everything will still appear normal.

Out of the box, Sitecore does not directly offer any solutions to this problem. Personally, I try and avoid Page Templates as much as possible. Fortunately there are several things you can do to solve this; easiest being to just go to your Site Root Page Template and remove the Header inheritance – fields will be gone and the world moves along. I’ve also seen a number of blog posts recently (although a specific one fails to come into memory right now) that deal with ways of hiding fields from the Content Editor for various reasons.

Making changes to Page Templates

Not really any different than before, but you do have a few more options available to you if you’ve followed the practices laid out in these posts.

In the example from above, you could also choose to just add your new “Component ZYX” to the Presentation Details of the Standard Values item and have its Datasource point to somewhere in your content repository where the marketing users can reach it. That way you avoid the problem of restricted access to Standard Values entirely.

And what if you had to solve the problem, of changing the content of “Component ZYX” based on where the News Article resided in the content tree?   Still not a problem; personalise the component using the Sitecore Rules Engine – like this for instance:

(I don’t have a Component ZYX, so I’ll pretend my Header component is it)

30-11-2013 14-17-47

Easy, but not so easily achievable had you been using the traditional Page Template approach. Or as I’d also like to put it; had you made The Page Template Mistake.

In summary

This will be the last post in the series “Creating good Sitecore Solutions”, but it will not be the end of what I have to say on this subject – not by a long shot. Everything I write about is based on my personal experiences, and I do follow the practices in these posts in my daily life as a Sitecore Consultant / Architect. I will keep posting about the experiences that come from this, and I also have a few tricks up my sleeve for solving some of the common issues that might arise, when working in the manner described here.

There are a few pitfalls, I’ll be the first to admit. But I’ll quickly add to that; the pitfalls I’ve encountered using this approach are by far less and fewer, than the problems I’ve been in when using Page Templates and components that clinged to them.

I hope – if nothing else – that the series has inspired a few new ideas out there :-)

Thursday, September 05, 2013

Working with Component / Data Templates

Avoiding the Page Template Mistake

This blog post is part 3 in a series on “Creating good Sitecore solutions”. Rather than constantly going back and adding edits to the previous posts, just follow this link to get an overview of the series.

A few thoughts

As promised in my last post; The Page Template Mistake; I will now attempt to put my money where my mouth is (so to speak) and provide something more concrete as to how the Page Template Mistake can be avoided, and how your implementation might carry forward without encountering it.

Before I do however, I will just clarify a few things that perhaps got lost in the previous posts.

I do believe that there is a time and a place for Page Templates. It just follows much later in the process and is a much more dynamic entity than what was certainly the case for my own solutions. I would not recommend content editors being forced to add any and all components to a blank “page canvas” for every page they create – we have Page Templates, Layout Presets and other technologies to help them out here.

What I advocate is, that you move the entire consideration of Page Templates much much further back in the process. Move it to the very end. Both to help you verify and assess components as the project comes about (if you’re tasked with that role), but also to help developers break free of the Page Template mindset entirely.

Your project will be better off for it.

My next post will be coming full circle, and demonstrate how Page Templates can be set up once you have all your Component Templates in place and – and I feel this point is important, because this used to be such a hassle for me in the past – how you can easily and quickly mock up new Page Templates as the situation requires, without breaking a sweat of what might break. Think yellow screens, think “Object Reference Not Set…” – all the common mishaps that you’ve experienced when tossing components onto a newly set up Page Template in the past.

Lastly; You’re not doing this specifically when “designing for the Sitecore Page Editor” as a few have suggested. That is a misunderstanding. What I am suggesting here is an approach that you would be taking if you’ve decided to make a good Sitecore solution. That it also happens to be a prerequisite for most meaningful work in the Sitecore Page Editor is consequential and accidental, you should not set out to “design for the Page Editor” at all.

After all – in doing so – you are inferring that this is a specific task, possibly an extra task. It is not. What I am suggesting is cost free, adds no overhead to your project. If done up front, that is. If you start by deciding to build a good Sitecore solution.

And on that note, let’s get to it.

Implementing a Component Template

To serve as an example, I’ll pick a component from the – in theory – up and coming CorePoint IT website (my own one-man consulting company). I say in theory because just as the mechanics own car, somehow working on this website always seems to end up fairly low on my priority list ;-)

I’ll pick something simple to start off with. In the HTML I’ve had done for the site, it looks like this:

04-09-2013 19-13-20

Looking at the HTML snippet for this component, it looks like this.

<div id="topBanner">
    <img src="images/banners/glass.gif" alt="" />
    <div id="topBannerContent">
        <h4>The company that does anything...</h4>
        <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.</p>
    </div>
    <a href="#">Read more >></a>
</div>

No big surprises there. Not too happy about the “id” attributes in there but let’s set aside that discussion for the time being.

I identify 5 tokens (tokens is a bad term. Anyone have another suggestion?) in there that I would like to see content managed on this component.

  • Heading
  • Body Text
  • Image
  • Link Text
  • Link

Breaking up the link near the bottom into two separate entities is a habit I’ve adopted. While it is possible on a Sitecore “General Link” for content editors to specify things such as Link Text; this doesn’t hold true for “Internal Link”. Doing it like this as a convention just saves a lot of grief.

Setting up the Component Template

04-09-2013 19-34-45

While this may look apparent, there are quite many (of my own) conventions in play here. I recommend you follow them, each of them will grant you “+2 to the overall Sitecore goodness feel”.

  • Give your component a good name. As “good” is subjective, here’s a few examples of component names that are NOT good (all of them from real life):
    • phInnerHeadingBox
    • HeroBoxTopRight
    • Content Spot
  • Set an icon for your Component Template. First thing, no delay. And while you can try and be creative and find an icon that “matches what your component does”, you will likely fail – the icon set is too generic for that. Don’t worry though, as it doesn’t really matter WHAT icon you choose – just that you choose one, and choose the same one in the steps to follow.
  • Place your fields in one “Section” named in exactly the same manner as your component.
  • Assign the icon from above, to that Section as well. Here’s how:
    04-09-2013 19-43-12
  • Name your fields, prefixed with the Component Name.
    • This is controversial, I know. But given that Sitecore does not distinguish Sections when addressing fields, and you cannot make any assumptions at this stage about the Page Template that your component will be living on (since you don’t know, and never will) – doing it like this provides the Path of Least Surprise later on.
    • Also keep in mind; field names mean nothing (really) when your content editor user is in the Page Editor – and given that the same user is given the context via the Section in the Content Editor, they won’t have much trouble scanning the fields for the one they need there either.
  • Set a short help text for each of your fields. This often overlooked step will mean a world of difference for your Content Editor users, takes you about 10 seconds per field (at this stage in the process) and grants you “Sitecore goodness” karma. If you haven’t done this before – try it. Take my word for it. Here’s how:
    04-09-2013 20-04-21

And you’re done. For now.

Setting up the Component

Proceed with your method of choice to set up the Sublayout Component in Sitecore. (Covering everything involved in this step probably could use a blog post of it’s own. I deem this out of scope for this one). Name it the same as your Component Template.

04-09-2013 20-11-03

Carry out these steps:

  • Set the icon for the Component to the same icon you chose for the Component Template.
    04-09-2013 20-13-34
  • Set the Datasource Template to your Component Template.
    04-09-2013 20-14-59

    04-09-2013 20-16-04
  • Finally take a snapshot of your component, and set up the Component thumbnail.
    • If your Component is part of a multi-site solution and look completely different between the sites, leave out this step. Sitecore requires customization to be able to do site-specific thumbnails, something I might cover in a later post. Tweet if you want it. @cassidydotdk ;-)

      If there is no thumbnail defined, Sitecore will show an enlarged version of your chosen icon for the component when adding it in the Page Editor. Not ideal, but still sticks with the established convention pretty good.
    • Set it up like this.
      04-09-2013 20-28-44

And that’s pretty much it. There may be additional things to consider when setting up your Component; Rendering Parameters and so on – I’m going to skip that for this post, as it doesn’t lean towards the points I am making here. I know I say that a lot, but hey… this post is going to be more than long enough already.

Implementing the Component

Like a TV chef, I’m going to skip ahead quickly and show you the resulting Sublayout .ASCX. The layout I’ve created does nothing but set up one Placeholder; “content” and include the relevant CSS files. For those of you riding the MVC wave, I’m sure you can adapt.

The .ASCX
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="Top Banner.ascx.cs" Inherits="Website.layouts.CorePoint.Top_Banner" %>
<div id="topBanner">
    <sc:Image runat="server" Field="Top Banner Image" ID="sciImage"/>
    <div id="topBannerContent">
        <asp:PlaceHolder runat="server" ID="phHeading">
            <h4><sc:Text runat="server" Field="Top Banner Heading" ID="sctHeading"/></h4>
        </asp:PlaceHolder>
        <sc:Text runat="server" Field="Top Banner Body Text" ID="sctBodyText"/>
    </div>
    <asp:PlaceHolder runat="server" ID="phLink">
        <sc:Link runat="server" Field="Top Banner Link" ID="sclLink">
            <sc:Text runat="server" Field="Top Banner Link Text" ID="sclLinkText"/>
        </sc:Link>
    </asp:PlaceHolder>
</div>

The codebehind is empty, at this point.

Creating a Data Item based on my Component Template

I then create an item, based on my newly created Component Template.

04-09-2013 21-27-47

And to further stress my point that Page Templates have no place at this point, I will just proceed to modify the presentation details of the default /content/home item that ships with Sitecore.

Setting up the Sitecore page

I change the presentation details for the item, to look like this. As mentioned; the Layout only holds the basics – and a placeholder keyed “content”.

04-09-2013 21-31-04

And finally I configure my Top Banner component to use my newly created Content Item as a datasource.

04-09-2013 21-32-58

After all this, I do a quick publish – and this is what I see. If I hadn’t read The Page Template Mistake or John Wests post on how to apply data sources to components, I might be surprised at this point.

04-09-2013 21-38-01

Nothing shows. Your first instinct might be to have a look at the page source. It looks like this.

04-09-2013 21-39-34

So essentially; the component gets rendered ok. There’s just nothing in it.

And this is the crust of the Page Template Mistake. Sitecore does nothing (for you) to respond to your configuration; setting the datasource to your content item. And I do believe this is the first reason many venture down that mistaken road and begin making the Page Template Mistake in the first place. There is no immediately obvious way to get to the datasource, and the standard Sitecore web controls don’t respond to it. So one retorts to hitting the Sitecore.Context.Item, and from here on out your fate is sealed.

Fortunately there’s a better way to approach this. Let’s introduce a bit of codebehind.

Implementing the Component code (basic)
public partial class Top_Banner : UserControl
{
    protected Item _actionItem = null;

    public Item ActionItem
    {
        get
        {
            if ( _actionItem == null )
            {
                var sl = Parent as Sublayout;
                if ( sl != null )
                {
                    if ( !string.IsNullOrEmpty( sl.DataSource ) )
                    {
                        Item datasourceItem = Sitecore.Context.Database.GetItem( sl.DataSource, Sitecore.Context.Language );
                        if ( datasourceItem != null && datasourceItem.Versions.GetVersions().Any() )
                            _actionItem = datasourceItem;
                    }
                }
            }

            if ( _actionItem == null )
                _actionItem = Sitecore.Context.Item;

            return _actionItem;
        }
    }

    protected void Page_Load( object sender, EventArgs e )
    {
        sctHeading.Item =
            sctBodyText.Item =
            sciImage.Item =
            sclLink.Item =
            sctBodyText.Item = ActionItem;
    }
}

And the result.

04-09-2013 23-42-10

This is more or less Datasource 101. Implement like this, and you are more or less imitating XSL Renderings and how $sc_item is set up to work by default.

Look here’s the thing:

If you do this, and you do it consistently, your solution is already in the top N percent of well implemented Sitecore solutions. Good solutions. DMS enabled solutions. Almost by default.

You can work your way up from here, and I will give a few examples of that. But it starts here. It starts by deciding that what you want to do, is build a good Sitecore solution. You could do nothing more than just this in your solution, and you’d have pretty much all DMS scenarios covered. I really am not kidding.

Just one gotcha; Sitecore 7 expands upon the Datasource concept. Since I am blogging in the context of personal experience and practices I myself have found to be successful – I cannot account for how the above code fits with Sitecore 7. I have no live sites under my belt at this stage that uses Sitecore 7. My initial guess would be; “it’s probably fine” however.

Implementing the code (intermediate)

The next natural step up from here would be to push the ActionItem code to a base class, and make all your Components inherit from here. Quite many of my readers of the previous posts in this series point this out – and until recently this has also been my own sole approach to this problem.

The base class could look like this.

public class BaseSublayout : UserControl
{
    #region :: Action Item ::
    protected Item _actionItem = null;

    public Item ActionItem
    {
        get
        {
            if (_actionItem == null)
            {
                var sl = Parent as Sublayout;
                if (sl != null)
                {
                    if (!string.IsNullOrEmpty(sl.DataSource))
                    {
                        Item datasourceItem = Sitecore.Context.Database.GetItem(sl.DataSource, Sitecore.Context.Language);
                        if (datasourceItem != null && datasourceItem.Versions.GetVersions().Any())
                            _actionItem = datasourceItem;
                    }
                }
            }

            if (_actionItem == null)
                _actionItem = Sitecore.Context.Item;

            return _actionItem;
        }
    }
    #endregion

    protected void ApplyActionItemRecursively()
    {
        var ai = ActionItem;
        foreach ( Control c in Controls )
            RecurseControls( c, ai );
    }

    private void RecurseControls( Control parent, Item actionItem )
    {
        if ( parent.GetType().FullName.StartsWith( "Sitecore.Web.UI.WebControls" ) )
        {
            var itemProp = parent.GetType().GetProperty( "Item" );
            if ( itemProp != null )
                itemProp.SetValue( parent, actionItem );
        }

        foreach( Control c in parent.Controls )
            RecurseControls( c, actionItem );
    }
}

And with this, every one of your components would look like this in their basic form. This is where my claim “this adds no cost to your solution”. I’ll say it again; implementing Components this way carries no significant overhead. You set up this base class once, and that’s it.

public partial class Top_Banner : BaseSublayout
{
    protected void Page_Load( object sender, EventArgs e )
    {
        ApplyActionItemRecursively();
    }
}

All I have left to do, is a slight bit of housekeeping. This is another convention I apply and if you stick to it, I am fairly confident your content editor users are going to love it.

public partial class Top_Banner : BaseSublayout
{
    protected void Page_Load( object sender, EventArgs e )
    {
        ApplyActionItemRecursively();

        if ( string.IsNullOrWhiteSpace( ActionItem[ "Top Banner Heading" ] ) )
            phHeading.Visible = false;

        if ( string.IsNullOrWhiteSpace( ActionItem["Top Banner Link Text"] ) )
            phLink.Visible = false;
    }
}

And that’s it, essentially. The Component is done. It’s well behaved, it can be used in M/V tests – call it “DMS Enabled” if you must. And if all your components are implemented in this manner, your life when creating Page Templates later on will be a heck of a lot easier. Painless is more like it. And it never cost you a dime.

For that, however, you are going to have to wait for the next post in this series.

You can stop reading now :-)

But for those persistent enough to make it this far in an already excessively long post; I’ll demonstrate where I am currently at myself in my pursuits of a mythological “best practice” in this area. I will be brief and post mostly code with minimal commentary. If you’re at this level of Sitecore implementation experience, I’m sure it will make sense.

Implementing the code (advanced)

The problem with the above approach is of course, as many commenters have pointed out. In real life, not all components fit nicely into this pattern. Sitecore themselves sort of indicate this as well; every default XSLT rendering has a $home variable defined (albeit commented out). Sometimes applying “Datasource or Context Item” just isn’t good enough.

Think Headers and Footer Components for instance. While you likely could be implementing a Datasourced Header component on one of your (deep) base templates, for many purposes this just isn’t practical.

Mark Ursino rightly mentions this problem in a comment;

“Global information (e.g. header and footer) cannot really be componentized too well unless you use standard values on a very low level "base page" template to assign the same header and footer data source items to all pages. I typically instead just define a predefined structure in a global area to support the header and footer.”.

Mark, I’m with you here, but I still believe that any component that “breaks out” of the imaginary “bounding box” that is its Component Template is creating an anti pattern in the solution – not unlike how Global Variables do it for traditional structured programming.

And there’s likely many similar scenarios.

Fortunately this can be resolved easily as well – without tweaking much in the code I just presented. AND – and this is important – without starting to make up a “meta CMS in the CMS” by adding global configuration structures and similar. I’ve taken this approach myself, and I always found them to be inhibiting me sooner or later in the lifetime of the solution.

Here’s what I suggest.

Have your components adhere to relevant strategies for resolving the ActionItem. Mostly – what I just lined out above will be fine. For some components, it would be more appropriate to EITHER respond to the Datasource (if set) or retort to $home. For others again; perhaps responding to Datassource (WHATEVER else you do; always always always respect the Datasource if one has been set. Always. Please. Having a “global header” that cannot be datasourced to make a quick micro-site is just a right pain) and retorting to crawling “up the tree” until you find an item that inherits from your Component Template.

It looks like this. I’ve abbreviated slightly. It’s going to be a long paste, so I’ll quit writing now and just let the code do the rest of the talking (mostly).

Until next time :-)

namespace Website.layouts.CorePoint
{
    public abstract class ActionItemStrategy
    {
        public abstract Item Resolve( Control c );
    }

    /// <summary>
    ///     Classic Datasource handling
    /// </summary>
    public class DatasourceOrContextItemStrategy : ActionItemStrategy
    {
        private Language _fallbackLanguage;

        public DatasourceOrContextItemStrategy( Language fallbackLanguage = null )
        {
            _fallbackLanguage = fallbackLanguage;
        }

        public override Item Resolve( Control c )
        {
            var sl = c.Parent as Sublayout;
            if ( sl != null )
            {
                if ( !string.IsNullOrEmpty( sl.DataSource ) )
                {
                    Item datasourceItem = Context.Database.GetItem( sl.DataSource, Context.Language );
                    if ( datasourceItem != null && datasourceItem.Versions.GetVersions().Any() )
                        return datasourceItem;

                    if ( _fallbackLanguage != null )
                    {
                        datasourceItem = Context.Database.GetItem( sl.DataSource, _fallbackLanguage );
                        if ( datasourceItem != null && datasourceItem.Versions.GetVersions().Any() )
                            return datasourceItem;
                    }
                }
            }

            return null;
        }
    }

    /// <summary>
    ///     Resolves the ActionItem by datasource and falls back to Site Root.
    /// </summary>
    public class DatasourceOrHomeItemStrategy : ActionItemStrategy
    {
        public override Item Resolve( Control c )
        {
            Item datasourceItem = new DatasourceOrContextItemStrategy().Resolve( c );
            if ( datasourceItem != null )
                return datasourceItem;

            Item home = Context.Database.GetItem( Context.Site.StartPath, Context.Language );
            if ( home.Versions.GetVersions().Any() )
                return home;

            return null;
        }
    }

    public class BaseSublayout : UserControl
    {
        protected Item _actionItem = null;

        public Item ActionItem
        {
            get
            {
                if ( _actionItem == null )
                {
                    _actionItem = GetActionItemStrategy().Resolve( this );
                    if ( _actionItem == null )
                        _actionItem = Sitecore.Context.Item;
                }

                return _actionItem;
            }
        }

        protected virtual ActionItemStrategy GetActionItemStrategy()
        {
            return new DatasourceOrContextItemStrategy();
        }

        protected void ApplyActionItemRecursively()
        {
            Item ai = ActionItem;
            foreach ( Control c in Controls )
                RecurseControls( c, ai );
        }

        private void RecurseControls( Control parent, Item actionItem )
        {
            if ( parent.GetType().FullName.StartsWith( "Sitecore.Web.UI.WebControls" ) )
            {
                PropertyInfo itemProp = parent.GetType().GetProperty( "Item" );
                if ( itemProp != null )
                    itemProp.SetValue( parent, actionItem );
            }

            foreach ( Control c in parent.Controls )
                RecurseControls( c, actionItem );
        }
    }
}

And with this in place, the individual Component implementations could “do nothing” – in which case they would just apply default behaviour. But for some cases, overriding this behaviour is desirable – so we configure these with simple overrides. A few examples.

Site Header Component
protected override ActionItemStrategy GetActionItemStrategy()
{
    return new DatasourceOrHomeItemStrategy();
}
Implementing Language Fallback

Make this your default sublayout, overriding the default I listed above.

protected override ActionItemStrategy GetActionItemStrategy()
{
    return new DatasourceOrContextItemStrategy( Sitecore.Globalization.Language.Parse( "en" ) );
}

Make up your own as you go along. Not too many though – or the point of this whole exercise gets lots completely. I can attest from experience however; just the two first strategies solved the very large majority of my component worries. And I don’t implement any meta-structures any longer to support neither menus, nor headers or footers, or pretty much anything else for that matter.

And the flexibility this approach gives me in setting up any and all Page Templates that my content editors require; is near phenomenal. More on that next time.

Wednesday, August 21, 2013

The page template mistake

How to recognise it and how to avoid it

This blog post is part 2 in a series on “Creating good Sitecore solutions”. You will find part 1; “How do I create a good Sitecore solution?” here.

Getting more, for less. Or even for free.

Having decided to create a good Sitecore solution, or even just “a Sitecore solution”, there is one thing you need to get right that adds more “good Sitecore value” to your solution above all other things you could be doing.

And the best thing about it is; it will (should) not add any costs to your implementation. If the practices lined out here are followed from the start, my own personal experience has shown me that your implementation time is not increased. In fact I would argue, following these guidelines will bring your overall implementation time down more than anything. And from whichever side of the table you are on – buying or selling a Sitecore solution – time will be money.

I will explain this in more detail, as I go along.

The problem with (most) Sitecore implementations.

In my first post in this series, I hinted that a very large majority of Sitecore solutions I come across in may day to day work were, to some extent, not entirely “fit for duty”. While some of the shortcomings can be put down to just this – the solutions were never truly designed to be good Sitecore solutions to begin with; the decision to to so was just plain never made. Most of them have a very fundamental architectural shortcoming in common. And this particular shortcoming – more than anything else – will nothing short of completely rule out pretty much any DMS scenario you can think of. Right then and there – one glitch, if you will, in the way these solutions were architected – and you can forget about the (in my view) most important set of features in Sitecore or possibly any CMS platform on the market today.

Before I go on, and step up high and mighty on my soapbox – let me be the first to admit this. Up until just a few years ago, I was happily designing and implementing Sitecore solutions following these same – faulty, as this post should demonstrate – practices and guidelines.

It wasn’t until around the beginning of 2012 and having just gone through a greenfield Sitecore 6.5 implementation that it dawned on me; the way I was perceiving and approaching basic Sitecore information architecture was just – well plain wrong. I recall asking on LinkedIn “Have you built a site yet, truly "true" to the changes in the 6.5 platform?” (Sitecore MVP group, for those who have access) – asking if anyone else had revisited the way they implemented Sitecore solutions following the release of Sitecore 6.5. It created a bit of debate, but nothing too ground shaking.

I was under the mistaken impression at the time, that it was Sitecore 6.5 and DMS that brought on these changes. Having mulled over this ever since, I now know that I was wrong. I know now that the way one is supposed to be implementing and architecting Sitecore for the solutions to end up “DMS ready” and being well on the way to becoming a “good Sitecore solution” dates back at least as far as Sitecore version 5. It might even be sooner, but I have little to no experience with Sitecore versions pre-dating version 5.

If you are still with me here, I think it’s about time I unveil what I believe to be at the core of the problem, in the way I was designing Sitecore solutions – and the problem in the vast majority of less than ideal Sitecore solutions I come across today.

The problem is: “Page Templates”

Yes indeed. Bear with me, and allow me to explain.

Having worked my way through I don’t know how many Sitecore releases dating as “far” back as Sitecore 5.1.1.12 (the earliest I have on record) and all the way up through to version 7 – it wasn’t until Sitecore 6.5 that Sitecore brought on a truly serious alternative offering to the ever popular “Sitecore Content Editor”. In fact the Sitecore Content Editor is so widely used that most people probably don’t even realise, this is just one content editor interface in Sitecore. To most I would bet; this editor IS “Sitecore”.

A quick re-cap. Sitecore 5 and version 6s prior to 6.5 did offer alternative interfaces. As far as I can tell however, nobody really used them. I practically never came across any implementations were these played any active role. You had to implement for these alternatives specifically (sc:Dot anyone?) and in my personal view they just plain didn’t work very well. In essence you had to do a fair amount of extra (key word here) development effort to support anything but the Sitecore Content Editor. And as I’ve already argued – time equals money – so it doesn’t get done. Only in the rarest of circumstances.

Along came 6.4 and in particular 6.5 – and changed all that. For the first time – at least for me – could one switch to this “new” Sitecore user interface (which is, in fact, not new at all) and see the site one was building become truly interactive. Without doing much if anything at all, to support it. Alright so there is a few things to consider, but I consider these insignificant in the grand scheme of things.

All of a sudden, teaching clients to do their work in the Page Editor became a viable option. And in many (most) cases a very strong alternative to the Sitecore Content Editor. I mean the Sitecore Content Editor is fine, if you’re working on Page Templates – marketing people will get that, and manage fine to go in and alter some headlines, swap out a few pictures and even add a few new pages (based on Page Templates) to the site. Not much more than that however, not in my experience.

The Page Editor, however, allows so much more than that. Following just the standard Sitecore implementation guidelines – the Page Editor allows the content editor to work with the very fabric of the page. Swapping out components, personalising components, M/V testing them with alternating content. And while all of these possibilities are also present in the Sitecore Content Editor, the Page Editor beats it by miles in terms of overall user experience for the average non-developer user.

And here’s the thing. Swapping out components, M/V testing components on a page, personalising components on a page. None of this – none of it – fits into the mindset of a “Page Template”. Your page has become a dynamic entity, something to be shaped and molded into nothing short of the “Perfect personalised user experience for your site visitors” – this is the way of the Digital Marketing Future. We’re going to the Moon and all that ;-)

The fact of the matter is; if you perceive each page on your site as something that fits the static nature of a Sitecore template – keep in mind, these can only be created by developers, and once a template has been set for an item it stays with the item forever. Or at least until you forcibly decide to change it. Also keep in mind, a template for “Page A” will also be the same template for any other pages of the same type as “Page A”. You can’t have the template holding X fields here, and Y fields there. Sitecore just isn’t designed for that (yet, I hope).

To overcome this, Sitecore uses Datasources. I think this was recently dubbed “Related Content” in a recent Sitecore release, but I’m going hardline and stick with the original term. “Feeding” your component with a Datasource is the way you instruct it to “go get your content from this place over here, don’t look at the page you happen to be sitting on”. None of this means anything to the Page Editor – it just shows (and allows edits of) the content from where ever it was sourced – whereas you need to jump around between items in the Sitecore Content Editor to achieve the same (reference: section 4.2.1 of the Content Authors Reference and Cookbook for Sitecore 6.6).

For both personalisation and M/V testing to work – your components must be able to be datasourced. No if’s, no buts'.

And this is it. This just doesn’t happen (much) in most solutions I visit. I, as most of the Sitecore developer community, implement the general term component as an ASP.NET User Control or the up-and-coming MVC alternatives. Sitecore also supports other types of components, most notably the “XSL Rendering” type of component. For a variety of reasons, this component type is being ruled out everywhere – performance reasons, lack of familiarity with the XSLT syntax among the developer base – the reasons are many. Rightfully so, I might add. It’s a relic from a time where Sitecore seemed to be designed on the idea, that the Sitecore data structure should be represented in abstract as one big XML Document – and transformed for multiple purposes by the up and coming XSLT technology. While Sitecore still supports this notion, the product is moving more and more away from this line of thinking.

So. When writing components in ones language of choice – I guess c# is the dominant choice these days, and working with a user base that exclusively accesses Sitecore through one common interface – the Sitecore Content Editor – you set yourself up for The Page Template Mistake.

The Page Template Mistake

While going through all the motions of setting up Page Insert options for your users, you would probably also be considering what fields to present to your users on each of these “pages” they can insert. If you’re doing this well, you will break down your Data Templates into smaller bits, so as to make them easily available for re-use across different Page Templates. So you’ll isolate your “Page Header” and “Sub Heading” fields into one Data Template – and then have some or most of your Page Templates inherit from this one, as well as any other Data Templates that the particular Page Type will support.

As the site evolves you shape and mold your Data Template structure, to make the best use possible of the common fields across pages.

You’ll begin to implement components – like a common “Left Menu” component for example – and have these traverse through your Page Items based on Page Templates – outputting a nice and nested logical representation of your site. The site visitor clicks elements on the menu, and navigates to a new page. The story repeats itself.

Eventually you’re done. The site launches, editors make the last minute changes to headers, round off corners of the images and changes a few icons to the Cornflower Blue. Everyone is happy.

Everyone is happy, that is, until 3 days into the launch and your pesky content editors decides to try out some of this “fancy M/V testing that we’ve heard so much about”.

You’ve just made The Page Template Mistake. Don’t worry though matey, so have I and so have we all.

You will find, that once the content editors start moving stuff around, adding YouTube Video Player Component onto the “Contact Us” page – you’re in trouble. Sure you can go; “oh we’re sorry. We didn’t make it so that this component can work on that page” but really all you’re doing at this stage is making up excuses and adding a healthy dose of CYA. I know I did.

If all your considerations when designing your page and template structure was focused around the Sitecore Content Editor (and it is an EASY trap to fall into – you DO do all of the designing and “architecting” in this very editor) – chances are slim to none that you have all the dynamics in place to allow the kind of flexibility the Page Editor truly inspires.

M/V testing?  “Uhm sure…” (muttered on the phone while desperately scrambling to add a few template Insert Options to the solution and hoping it will work).

Ever been there?

Fortunately there’s an easy way to avoid it. Not an easy fix, mind you, refactoring your solution AFTER the fact is going to be a fairly extensive job. Avoiding this problem however, adds no cost to your solution implementation AND puts you on the road to delivering a “good Sitecore solution”.

The Data Template solution

If you look closely in the Sitecore documentation, you will find the term Data Template everywhere when speaking of content and data structures. In fact I don’t recall anywhere within official Sitecore documentation seeing the term “Page Template” mentioned. I could be wrong though, there is a vast amount of cookbooks dealing with these topics. Here’s a tip:

Don’t think Data Template, think “Component Template”.

Because that’s what you should be doing.

When going through the site designs, part of that process is identifying “Components” that has to be built for the site to be completed. You do this already – regardless of whether you’re thinking in terms of Page Templates or not. Each of these components will have a certain number of Sitecore fields supporting them. It will be the obvious ones; “Image Heading”, “Image”, “Subtitle”, “Citation” and so on – we all know how these look and work. There will (should) also be the more subtle ones like “Banner Rotation Delay”, “Allow Fullscreen” and so on. You won’t necessarily recognise all of these at the get-go, but don’t worry. These can be added as you go along with the implementation. Make sure you do, though. Things like “Banner Rotation Delay” are perfect candidates for M/V testing. Try it, you’ll probably be as surprised as I was about the difference it can make.

This is what should be defining your Component Template. A Component Template for a Component – this makes perfect sense. Name them by convention; a “YouTube Video Template” matching the “YouTube Video” component. This makes sense. To you and to your content editors alike. While configuring each component in Sitecore, make sure you configure the components Datasource Template to point to your corresponding Component Template – and you’re already more than half way on your pursuit of the “good Sitecore solution”.

Forget about Page Templates at this stage. You can do them at the end. At the very end of the project, I’m serious. Keep working your way through components and if you’re fortunate enough, get your team of developers started on implementing them right away. If not, start doing them yourself. Just make sure that the implementation of these components follow one of the most basic of rules:

Make sure the component respects it’s data source.

Mine didn’t. Not until that epiphany I had with Sitecore 6.5. As so many others, I implement my components as a Sitecore “Sublayout” (essentially an ASP.NET User Control) – and I would frequently sport code such as the following (not literally – the example code is ghastly, but am making a different point):

if ( Sitecore.Context.Item[“show in menu”] == “1” )
{
    litMenu.Text += “<li>” + Sitecore.Context.Item[“menu title”] + “</li>
}

Right up there on The Page Template Mistake, page 1, subheading “Sitecore.Context.Item”. Don’t use it. Well don’t use it in general, there are obviously cases where it is perfectly acceptable to go visit Sitecore.Context.Item.

What you need is something to the effect of (pseudocode, this post is already long enough without me diving in to a long technical explanation. I will do a follow-up post with concrete code examples to follow this one, I promise):

IF this_component HAS DEFINED Datasource
    SET $ActionItem TO Datasource
ELSE
    SET $ActionItem TO Sitecore.Context.Item

And then have all the component implementation respect draw its data exclusively from $ActionItem.

That’s all there is to it. Really. And since you’re ignoring Page Templates for now, testing and verification of the implemented components becomes very easy. Developers will be forced to add their components to “blank canvasses” as they go along and Datasource them to their items based on the respective Component Templates.

This is not new. This is not something “clever” I am making up, or a “clever idea I just had”. No my faithful reader – this principle sits at the very foundation of Sitecore presentation architecture. This behaviour has been expected from the very beginning (of Sitecore 5, maybe sooner) from every Component.

This is $sc_item versus $sc_contentitem in your (no longer used) XSLT renderings; one of the first types of components you could implement in Sitecore. Also known as a “Rendering” – a term still being broadly used today to cover most anything used to output content. I prefer the Page Editor term Component.

$sc_item would behave exactly like the pseudocode above.

A rendering can retrieve data from its data source item. The $sc_item variable represents the data source item for an XSL rendering. If the developer does not specify a data source item for a rendering, the default data source item is the context item, and $sc_item and $sc_currentitem are the same item. – Presentation Component XSL Reference section 3.2.1.

And while I have found little to no documentation in Sitecore actually specifically instructing you to be designing Component Templates in the manner I describe, I can tell you this much: If you want to support all the DMS goodness that everyone is talking about these days – this is the first step.

Forget about Page Templates; think Component Templates.

Do this from the start, and your solution will come into existence, ready and waiting to be M/V tested, personalised and whatnot. At no extra cost. Creating your information architecture in this manner from the ground up will add no extra time to your project. In fact I have found that it subtracts slightly from the implementation time.

And on that note, I think it’s time I step down from my soapbox. I will follow-up this post with a more technically to-the-point post explaining and demonstrating how an information architecture can come into place, following these principles. Also a few pointers to how your components can easily adapt these principles and finally; “what DO we do with Page Templates then?”.

Until then.