Programmatically Add Controls to the HTML Head in Sitecore

I was recently working on a Sitecore module and realized I needed to add some HTML elements to the <head> tag of pages using the module. This would normally be something that can be done directly in every layout, but because this is a Sitecore module, I wanted to do it dynamically via C# through a pipeline so that it would only require a configuration patch to inject my code. The challenge I had was not implementing it via a pipeline processor, but rather programmatically getting access to the <head> tag. Luckily, John West had a great solution, and it was something directly available via the Sitecore API.

First, to accomplish this, register a processor for the renderLayout pipeline:

<renderLayout>
  <processor type="MyLibrary.Pipelines.RenderLayout.InsertHeadControls, MyLibrary">
  ...
</renderLayout>

Next, let’s look at the code:

namespace MyLibrary.Pipelines.RenderLayout
{
  public class InsertHeadControls
  {
    public void Process(RenderLayoutArgs args)
    {

      // no need to run our code in the shell
      if(Sitecore.Context.Site.Name == "shell")
        return;

      Control head = WebUtil.FindControlOfType(Sitecore.Context.Page.Page, typeof(HtmlHead));
      if(head != null)
      {
        head.Controls.Add(/* add whatever control you want */);
      }
    }
  }
}

The key here was to use WebUtil.FindControlOfType() to get the HtmlHead control via C#. From there you can ensure its not null and add controls dynamically to it as needed. Note: for the HtmlHead to not be null, I believe this requires a runat="server" on the <head> tag.

 

Mark Ursino

Mark is Sr. Director, CMS Practice Lead at Rightpoint and a Sitecore Technology MVP.

 

Leave a Reply

Your email address will not be published. Required fields are marked *

 

This site uses Akismet to reduce spam. Learn how your comment data is processed.