MVC Style Sections in Sitecore

Components (renderings) within Sitecore are discrete entities that can be placed on page template, allowing editors to build up pages in a consistent manner, and allowing reuse of components through out the site.

One issue with component based architecture in sitecore is the handling of CSS and JS files that are  associated with a component.  Typically we would want CSS to be loaded in the head, and JS to be loaded at the bottom of a webpage.  How does this work with a component based architecture?  as the component should be self contained, with the JS/CSS and Html needed for it to display, how to we push all the assets that a compoennt needs to the top or bottom of the page?

MVC Sections

Typically within a website using ASP.NET MVC, we’d use MVC sections to add js and css to the correct place in the page.  Unfortunately, sitecore doesnt support MVC sections from within renderings, so we need to find another way to mimic this behaviour.

Enter sitecore MVC sections

Sitecore MVC sections is a solution to this problem that enables MVC section like functionality from within sitecore. It makes use of a feture of ASP.NET called request filters.  This can be utilised as follows:

  1.  Specify in your layout a section where content in a view can be placed

2. In your rendering wrap any content that you want to be added to a section in the layout in the BeginSitecoreSection using statement

@using (Html.BeginSitecoreSection("ViewHeadScripts"))
  <link rel='stylesheet' href='http://mysite.com/component.css' type='text/css' media='all' />

In the sample code on GitHub a pipeline (SitecoreMVCSectionPipeline) is added to httpRequestBegin which sets the reposne filter in the request.  The response filter then takes care of moving the sections to the correct area in the layout.  Voila! We now have a completely self-contained component, that can be added to any page.  The good thing about this solution, is that it requires no amendments to any of Sitecores caching capabilities, so no mattrer how components are cached, the correct CSS and JS will appear on the page.

Leave a Reply

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