Dynamic Placeholders for Sitecore MVC

Posted by Xing Liu on 1/5/2015

We all know that placeholders are an integral part of Sitecore, allowing us to add various components on a page that we have developed. You can even nest placeholders, so that a component placed in one placeholder can offer another placeholder that can house even more components. However, when you nest placeholders, you may get into a strange situation… Basically, if I have more than one component with a placeholder on a page, how does Sitecore know which placeholder I’m adding additional components to? The answer is that Sitecore doesn’t know, and you may get into a situation where components are randomly placed into the placeholders of the parent components. This happens, of course, because the placeholders have the same name and because more than one now exists on the page. Sitecore essentially can’t differentiate between them. How can we get around this? Dynamically named placeholders are the way.

First, you need to add a DynamicPlaceholder class that will extend the Sitecore.Mvc.Helpers class. This basically will add an additional function that will allow you to create a dynamic placeholder, much the same way you create a regular placeholder.  In this class, you can concatenate the placeholder key with the current rendering unique id. This essentially will make the placeholder unique on the page, no matter how many times it exists.

helper.Placeholder(string.Format("{0}_{1}", placeholderKey, currentRenderingId));

Make sure the namespace of the new code is added to the web.config in the Views folder of your MVC project.  After that, in your view rendering file, you can create the dynamic placeholder as follows:

@Html.Sitecore().DynamicPlaceholder("yourPlaceholderKey")
Then, we’ll have to tap into the Sitecore pipeline in two places.  The first one is to assign placeholder settings to the dynamic placeholder so that you can add controls into that placeholder.  This is mainly because we added a DynamicPlaceholder with unique id, but the placeholder settings are only targeting one static placeholder key. So this hook into the pipeline allows us to bind placeholder settings to each dynamic placeholder.  The second tap into the pipeline is to remove the long unique id from each placeholder in page editor mode (or PLD) to be more readable for content authors.

That’s all you need to create dynamic placeholders for Sitecore.  Dynamic placeholders will come in handy when you are dealing more than one components with the same placeholder.  



CONTACT SYMSOFT SOLUTIONS

Looking for a partner who will exceed your expectations? Get in touch.

Name
*
Message
*
SYMSOFT SOLUTIONS 4090 Truxel Road, Suite 200 Sacramento, CA 95834
United States (916) 567-1740