Programmatically Add Controls to the HTML Head in Sitecore

Jan 19, 2012 by Mark Ursino    No Comments    Posted under: 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.

Got anything to say? Go ahead and leave a comment!

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

 

Categories