Saturday, 8 September 2018

Sitecore 9 Dynamic Placeholders And Why we need them

As many of us have faced the issue of repeating content when trying to use same placeholder name, Sitecore 9 has filled this gap by introducing support for Dynamic Placeholders in Out of the Box installation.

Problem Statement and when to use Dynamic Placeholders:
In the below example I will reproduce an issue when I use a standard Sitecore placeholder:
That is:

I have created here:

  1. Layout.cshtml  - A layout file with 3 placeholders: Header, Main, Footer
  2. Sublayouts 
      • Section - A sublayout view with following code:
      • 1 Column - A sublayout view with following code.
  3. A Hero image component - This a sample component for example. We can use any other component. It contains 2 fields: Title, Image.
Important Note: None of the above placeholders will allow us to add a rendering in it if we don’t create a placeholder setting item for them under: /sitecore/layout/Placeholder Settings.

Now, if I want to place 2 different Hero images on the page with 1 column width, I will perform the following steps:
  • Run the page with above Layout attached in the experience editor mode
  • Click “Add here” to add “Section” rendering in “main” placeholder:

  • Now add “1 Column” inside the “Section”.
  • Finally add the Hero  Image Component:

Now, if I want to reuse the 1 Column sublayout and add it inside the section below the  column already added:
I will get the same component pre-populated which I added inside the first “1 Column”, which is not what we want as we should be able to add any other component in it with different datasource:
The presentation details looks like this:

This restricts us to reuse the 1 Column sublayout as the placeholder used is the having same name.
Solution to above issue can be achieved by creating separate placeholders and restricting users to add limited component or using Dynamic Placeholders:

Now, if we update the following to use Dynamic Placeholders:
  1. Section.cshtml:
  2.           1 Column.cshtml:

The above “DynamicPlaceholder” method can be found in SitecoreHelper class which is part of Sitecore.Mvc assembly.
It has following overrides:

First parameter: Name of placeholder.
Second is Count: Number of times we want to render the placeholder. (the sublayout html will be created the number we give here). It will be useful for creating 2, 3, 4 etc. column sublayouts.
Third is the max count: Which represents the maximum number of times a content author can use the placeholder.
Forth is the seed count: It is the starting number that the suffix will use.

Experience editor will now allow us to add a different component:

After adding the second hero image the pages now has two 1 column sublayouts inside section with different hero images:

If we now see the presentation details from the content editor:
Each Hero image rendering has a different unique placeholder.

No comments:

Post a Comment