Easy and Reusable HTML Title Solution for Sitecore

Piggy-backing from my previous post, I wanted to propose a solution for something that is rather universal (every site/application needs it) but is pretty straight-forward.  It’s built on the interplay of an item representing the site as a whole with the individual pages that are served under it.  That specific feature is the HTML title (<html><head><title>).  Even better, this is an approach that should be 100% reusuable from site to site, project to project.

Normally, HTML titles should be a combination of a description of the current page as well as the larger site they are a part of.  Depending on who you ask, the order of the site or page-specific information could be flipped but a good example would be something like “Home | Example Site”.  What we’re going to implement would allow us set all HTML page titles as a combination of these elements that allows for both individual and sweeping changes.

It starts with the best practice of defining all template fields (and their related template section) as individual templates.  I group them together as “Field Sections”.  In the C#/.NET sense, I think of these sort of like properties on an interface.  The two field sections we’ll define are “Site HTML Information” and “Page HTML Information”.

findgnosis - sitecore html title - 001

Since the fields are defined in their own templates, we can add them to any new or existing templates.

findgnosis - sitecore html title - 002

findgnosis - sitecore html title - 003

If you can tell from the fields “Site HTML Title Format” and “Page HTML Title”, our plan is to use the site’s format and inject the specific page title into it via String.Format.  So an example for the field on the site item:

findgnosis - sitecore html title - 004

And the individual page:

findgnosis - sitecore html title - 005

Now time for some actual code.  Building off of having a Sitecore item that represents the site item in the content tree, we could write a static property like this:

        public static string HtmlTitle
        {
            get
            {
                return string.Format(SiteItem["Site HTML Title Format"], Sitecore.Context.Item["Page HTML Title"]);
            }
        }

And we can use that static property within an MVC Razor view layout:

<title>@Sitecore75Sandbox.Utility.HtmlTitle</title>

I’m personally not worried about it having hooks into the Page Editor since this is buried in the head of the page and isn’t visual to the end user.  But you can do additional steps to make that happen.

None of this is rocket science but it is streamlined and discrete enough you can use it on most any project.

Leave a Reply