Sitecore Cookbook for Developers

4.6 (5 reviews total)
By Yogesh Patel
    Advance your knowledge in tech with a Packt subscription

  • Instant online access to over 7,500+ books and videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies
  1. Basic Presentation Components

About this book

This book will get you started on building rich websites, and customizing user interfaces by creating content management applications quickly. It will give you an insight into web designs and how to customize the Sitecore architecture as per your website's requirements using best practices.

Packed with over 70 recipes to help you achieve and solve real-world common tasks, requirements, and the problems of content management, content delivery, and publishing instance environments. It also presents recipes on Sitecore’s backend processes of customizing pipelines, creating custom event handler and media handler, setting hooks and more. Other topics covered include creating a workflow action, publishing sublayouts and media files, securing your environment by customizing user profiles and access rights, boosting search capabilities, optimising performance, scalability and high-availability of Sitecore instances and much more.

By the end of this book, you will have be able to add virtually limitless features to your websites by developing and deploying Sitecore efficiently.

Publication date:
April 2016
Publisher
Packt
Pages
338
ISBN
9781784396527

 

Chapter 1. Basic Presentation Components

In this chapter, we will see how to build pages in Sitecore with the help of different rendering techniques using different Sitecore presentation components. You will learn the following recipes:

  • Creating a simple content page using template and layout

  • Creating a sidebar menu using view rendering and RenderingModel

  • Creating breadcrumb using the view and custom model

  • Creating carousel using view and controller renderings

  • Placing renderings dynamically using placeholders

  • Empowering the Experience Editor using placeholder settings

  • Restricting or swapping rendering controls on placeholders

 

Introduction


If you are reading this book, you already know that Sitecore XP (Experience Platform) is not only an enterprise-level content management system (CMS) but also a web framework or web platform. Sitecore has robust and in-depth APIs to offer maximum flexibility to developers to implement custom solutions. It has many features designed to support enterprise-level requirements.

Sitecore provides extensive out-of-the-box components such as layout, device, placeholder, and some rendering controls, which play important role in designing and editing interfaces. We can also develop custom rendering components using Extensible Stylesheet Language Transformations (XSLT), ASP.NET Web Forms, and Model-View-Controller (MVC) frameworks to render content to the pages. All these frameworks currently exist in Sitecore, but MVC is now becoming widely used in Sitecore solutions and also provides better options compared to Web Forms and XSLT. Hence, we will prepare all the recipes using the MVC framework.

This chapter first serves recipes to create rendering components using model, view, and controller, and then explains how we can integrate them with Sitecore's out-of-the-box components. Looking into the depth of presentation components, you will learn extending these components in the next chapter.

Note

For this chapter, it's required that you create a Visual Studio solution. You can refer to Appendix A, Getting Started with Sitecore, which explains how you can set up Sitecore solutions. Make sure that you have added a reference of Sitecore.Kernel.dll and Sitecore.Mvc.dll files to the SitecoreCookbook project.

 

Creating a simple content page using template and layout


As a developer, you will first have to understand the architecture of how a web page works. To create web pages, you first need to create a data structure using data templates, based on which you can create content items. Layout is used to place content with some presentation logic on it. In this recipe, we will take a quick look at creating a simple content page showing the title, body, logo, and other details.

How to do it…

We will first create and define a data template for the Home item (that is, home page):

  1. Log in to Sitecore. Open the Content Editor from Launch Pad. You will find a default /sitecore/Content/Home item with the Title and Text fields. Delete this item as we will create our own custom template for the Home item.

  2. In the /sitecore/Templates item, create a new Template Folder item, Cookbook. In this, create a Site Root template, leaving the base template set to the default Standard template, as shown in the following image:

  3. In template builder, create different fields, Title and Body, as shown in the following image, and save the details:

  4. We will now create a content page using this data template. Create a new content item, Home, in the /sitecore/Content path using the Site Root template that we created and fill in the appropriate information in these fields:

  5. To show common details of websites, such as logo, copyright text, and some other information, create another Site Configuration template with fields such as Company Name, Logo, Copyright Text, and so on.

  6. The Site Configuration item will be a non-visual item, so it should be created outside the Home item. Create a folder item Global in /sitecore/Content, and in this, create a content item, Configurations, using the preceding template, and fill in the appropriate details.

  7. We will now create a layout from Visual Studio. From the SitecoreCookbook project, create an MVC main.cshtml view in the /Views folder to render field values from the previously created items. For this, put the following code in the view file inside the <h tml/body> tag:

    <div id="header"> <a href="/">
      @Html.Sitecore().Field("Logo", Sitecore.Context.Database.GetItem("/sitecore/Content/Global/Configurations"))
    </a> </div>
    
    <div id="contentarea">
      <h1>@Html.Sitecore().Field("Title")</h1>
      @Html.Sitecore().Field("Body")
    </div>
    
    <div id="footer">
      @Html.Sitecore().Field("Copyright Text", Sitecore.Context.Database.GetItem("/sitecore/Content/Global/Configurations"))
    </div>
  8. We will now register this view file as a layout in Sitecore. In the /sitecore/layout/Layouts item, create a layout folder, Cookbook. In this, create a layout named Main Layout. Set the path field of this layout to /Views/main.cshtml.

  9. Now we will assign the layout to the content items. Select the Site Root data template. From the ribbon, select Standard Values in the Builder Options tab. This will create the __Standard Values item for the template.

  10. Select the __Standard Values item. From the ribbon, select the Details button in the Layout group from the Presentation tab. It will open a Layout Details dialog. For a Default layout, click on the Edit button, which will open the Device Editor dialog. Here, in the Layout section, select Main Layout and select OK. See the following image, which represents both the dialogs:

    Tip

    Instead of standard values, you can also assign a layout directly to the Home item. However, it's a recommended practice to apply presentation components to a template's standard values so that all items created from the template will inherit the field values from standard values.

  11. From the Content Editor, select the Home item. From the ribbon, click on the Preview button in the Publish group from the Publish tab. This will open your home page in preview mode, as shown in the following image, where you will find Logo, Title, Body, and Copyright Text.

    Note

    You can get the layout and style sheet files from the code bundle provided with this book to make it work, as shown in the following image:

Tip

Downloading the example code

You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

You can download the code files by following these steps:

  • Log in or register to our website using your e-mail address and password.

  • Hover the mouse pointer on the SUPPORT tab at the top.

  • Click on Code Downloads & Errata.

  • Enter the name of the book in the Search box.

  • Select the book for which you're looking to download the code files.

  • Choose from the drop-down menu where you purchased this book from.

  • Click on Code Download.

You can also download the code files by clicking on the Code Files button on the book's webpage at the Packt Publishing website. This page can be accessed by entering the book's name in the Search box. Please note that you need to be logged in to your Packt account.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

  • WinRAR / 7-Zip for Windows

  • Zipeg / iZip / UnRarX for Mac

  • 7-Zip / PeaZip for Linux

How it works…

Sitecore layouts are reusable ASP.NET Web Forms (.aspx) or MVC views (.cshtml) that you register with Sitecore. ASP.NET uses Web Forms or views to serve HTTP requests. Here, on requesting the Home item, Sitecore first reads the item and renders the physical file of the layout associated with the item.

In the view file, we used the Sitecore field helper, @Html.Sitecore().Field(<field name>), to render the Title and Body field values from the context item (in our case, Home). This helper method can also render a field of items other than the context item, which we used in order to render the Logo and Copyright Text fields of the Configurations item, @Html.Sitecore().Field(<field name>, Sitecore.Context.Database.GetItem(<ItemId or path of item>)).

Here, the Sitecore.Context.Database.GetItem() method provides the Sitecore.Data.Items.Item object, which has a collection of all the field values associated with the item.

Note

To learn more APIs, download Sitecore Presentation Component API Cookbook (https://goo.gl/fu99Vh). It provides APIs from Sitecore 6.4 or later with examples of Web Forms or Web controls, but they are still valid for Sitecore 8 or later with MVC as well.

Apart from the Content Editor, Sitecore also provides another tool, Experience Editor, to view pages in editing mode. From the ribbon, click on the Experience Editor button in the Publish tab to open an item in the Experience Editor. You can open it from Launch Pad as well. Here, you can change field values (for example, Body in the following image) rendered on the layout or view:

To disable content editing for an item field, you can pass additional parameters to the field helper, as shown in the following code:

@Html.Sitecore().Field("<field name>", new {DisableWebEdit=true})

You can also customize its rendering behavior by extending the Sitecore helper class. You can learn this from https://goo.gl/ZHruKe and http://goo.gl/Kx8MQl.

 

Creating a sidebar menu using view rendering and RenderingModel


In the previous recipe, you learned rendering simple field values in the layout itself. In this recipe, we will create a sidebar menu control using view rendering and RenderingModel and place them statically on layouts.

Getting ready

For this recipe, we will use the same layout file created in the previous recipe.

How to do it…

We will first create a template with some common fields required on all the content items of the site:

  1. Create one Common Fields data template with the Title, Body, Show in Menu, Image, and Icon fields. From its standard values, set Title as $name and tick the Show in Menu checkbox field. Also, from Layout Details, assign Main Layout to it, which we created in the previous recipe:

    We will first create different subitems inside the Home item so that we can have enough items to render menu control properly. Here, $name entered in the Title field is a standard value token so that the name of the item will be stored in the Title field for newly created items. You can learn more about standard value tokens at http://goo.gl/qUE85h.

  2. Create a few templates, for example, Product Section, Product Category, Product, and others. From their base template field, select the Common Fields template so that these fields, along with layout details, can get inherited to all these templates.

  3. Create content items under the Home item, following the /Home/<Product Section>/<Product Category>/<Product> hierarchy, and fill in their Title, Body, and other fields' values. For example, refer to the following image:

  4. Now, we will create a menu control to show all items created on the same hierarchical level of the context item. From Visual Studio, create a SideMenu.cshtml view in the /Views/Navigation folder and write the following code in it:

    @model RenderingModel
    <ol class="sidemenu">
      @foreach (var item in Model.Item.Parent.Children.ToArray())
      {
        if (@item["Show in Menu"] == "1")
        {
          <li>
            <a href="@Sitecore.Links.LinkManager.GetItemUrl(@item)">
              @item["Title"]
            </a>
          </li>
        }
      }
    </ol>
  5. Now we will register this view in Sitecore. Select /sitecore/layout/Renderings/, and create the Cookbook folder. In this, create a view rendering Side Menu and enter the view file path in the Path field, as shown in the following image:

    Tip

    It's good practice to assign an icon to each rendering, which will increase usability for content editors while working from the Experience Editor.

  6. In Main Layout or main.cshtml that we created in the previous recipe, place the following code in the appropriate place to render the menu on the page. Remember to update the item ID of the Side Menu rendering in this code:

    <div id="sidemenu">
      @Html.Sitecore().Rendering("{2383A57F-21FF-4A77-9E2A-C467F0CEDA57}")
    </div>
  7. Now, preview any product item; you will find that all the items at the same hierarchical levels will be displayed, as shown in the following image:

In the same way, you can also create top menu rendering. You can find its TopMenu.cshtml and SiteHelper.cs code files from the code bundle provided with this book.

How it works…

Sometimes, we get a requirement to hide an item from the menu, which requires having a common field such as Show in Menu or Hide from Menu in all items under Home. So, here we created the Common Fields template with the most common fields and inherited it in other data templates rather than duplicating these fields in all templates.

Note

Use Template inheritance to reuse content definitions, which makes a developer's life easier while doing further changes in it. Read best practices for template inheritance at http://goo.gl/1ePTtF.

We generated a simple menu using a view rendering. A view accepts a view model, which can be defined in the @model directive to determine the type of the model. If you don't specify the directive, Sitecore by default passes its default model, Sitecore.Mvc.Presentation.RenderingModel, which passes the context item to the view. You can also pass custom models to views, which you will learn in the next recipe.

In step 6, we bound the view statically (hardcoded on layout), which is also called static binding, and Sitecore provides two approaches for this:

@Html.Sitecore().Rendering("{2383A57F-21FF-4A77-9E2A-C467F0CEDA57}")
@Html.Sitecore().ViewRendering("<view file relative path>")

In the first approach, Sitecore itself finds the view definition from the view rendering registered in step 5. In the second approach, we can directly write the path of the view file.

There's more…

Here, we rendered the Side Menu view from its parent view Main Layout. Nested views can be very useful in reusing view renderings. For example, if you need to render a list of child items in different places, for example, news, events, products, and so on with the same interface, then you can achieve all this using a single view rendering!

 

Creating breadcrumb using the view and custom model


In the previous recipe, you learned creating a simple menu using a view with the default RenderingModel. In this recipe, we will create breadcrumb using a view and custom model.

Getting ready

For this recipe, we will use the same layout and items created in the previous recipes.

How to do it…

We will first create two classes: a simple BreadcrumbItem and BreadcrumbList. Here, BreadcrumbList will contain a list of BreadcrumbItem objects.

  1. In the SitecoreCookbook project, create a BreadcrumbItem class in the Models folder. This class will contain properties useful to render breadcrumb items. We inherited this class from Site core.Data.Items.CustomItem to implement custom items:

    public class BreadcrumbItem : CustomItem
    {
      public BreadcrumbItem(Item item)
        : base(item) {Assert.IsNotNull(item, "item");}
    
      public string Title
      {get { return InnerItem["Title"]; }}
    
      public bool IsActive
      {get { return Sitecore.Context.Item.ID == InnerItem.ID;}}
    
      public string Url
      {get { return LinkManager.GetItemUrl(InnerItem); }}
    }
  2. In the SitecoreCookbook project, create a rendering BreadcrumbList model class in the Models folder, which will make a list of all the breadcrumb items. Make sure that it inherits the Sitecore.Mvc.Presentation.RenderingModel class so that Sitecore will automatically invoke its Initialize() method when the view is invoked:

    public class BreadcrumbItemList : RenderingModel
    {
      public List<BreadcrumbItem> Breadcrumbs { get; set; }
      public override void Initialize(Rendering rendering)
      {
        Breadcrumbs = new List<BreadcrumbItem>();
        List<Item> items = GetBreadcrumbItems();
        foreach (Item item in items)
        {
          Breadcrumbs.Add(new BreadcrumbItem(item));
        }
        Breadcrumbs.Add(new BreadcrumbItem(Sitecore.Context.Item));
      }
    }
  3. Create the GetBreadcrumbItems() method to collect a list of breadcrumb items as follows:

    private List<Sitecore.Data.Items.Item> GetBreadcrumbItems()
    {
      string homePath = Sitecore.Context.Site.StartPath;
      Item homeItem = Sitecore.Context.Database.GetItem(homePath);
      List<Item> items = Sitecore.Context.Item.Axes.GetAncestors()
        .SkipWhile(item => item.ID != homeItem.ID)
        .ToList();
      return items;
    }
  4. We will now register this model in Sitecore. From the Content Editor, select the /sitecore/layout/Models item. Create a Cookbook folder, and create a BreadcrumbItemList model in it. Set the Model Type field value to the fully qualified type name of this class, as shown in the following image:

  5. Now we will create a view to render breadcrumb items. In the SitecoreCookbook project, create a Breadcrumb.cshtml view in the /Views/Navigation folder. Set the created BreadcrumbItemList model in the @model directive. Place the view content as follows:

    @model SitecoreCookbook.Models.BreadcrumbItemList
    <ol class="breadcrumb">
      @foreach (var item in Model.Breadcrumbs) {
        <li>
          @if (@item.IsActive)
            { @item.Title }
          else { 
            <a href="@item.Url">
              @item.Title
            </a>
          }
        </li>
      }
    </ol>
  6. Register this view in Sitecore, and remember to assign the registered model to this view. So, when the view is invoked, Sitecore will initialize the mentioned model to collect the breadcrumb item list and pass it to the view:

  7. In the same way as the previous recipe, place this breadcrumb view rendering in Main Layout so that it will get applied to all the items having this layout. Use the following code for this, and update the item ID of the view rendering in the code:

    <div id="breadcrumb">
      @Html.Sitecore().Rendering("{764C9697-EA31-4409-8208-0CAECBD76500}")
    </div>
  8. Now, preview an item; you will find the breadcrumb on the site, as shown in the following image:

How it works…

Here, we built breadcrumb using a custom RenderingModel. For this, we should either inherit the Sitecore.Mvc.Presentation.RenderingModel class or implement the Sitecore.Mvc.Presentation.IRenderingModel interface.

The Sitecore MVC framework gives a nice feature of invoking a model to pass data to the view without creating a controller. For this, in step 6, we mapped the model to our view rendering. In the next recipe, you will learn how to use controller rendering with the view.

See also

If you are interested in knowing how Web control and sublayout works, you can find a working sample of breadcrumb and Side Menu from the code bundle provided with this book. As an alternative, you can also learn basic Web Forms components from https://goo.gl/nlX3Cp.

 

Creating carousel using view and controller renderings


In the previous recipe, you learned how to use a custom model to pass data to the view using RenderingModel. In this recipe, we will create carousel using controller rendering and view rendering.

How to do it…

We will first create a template to generate carousel slides:

  1. Create a Carousel Slide template, as shown in the following image. Set the Source property of the Image field so that a user can pick carousel images directly from the source media folder. Do the same for the Link Item field.

  2. Create some carousel slide content items with appropriate field values.

  3. We want to show some selected carousel slides on our Home page, so we will add the tree list type carousel slides field to the Site Root template so that we can select multiple carousel slide items, as shown in the following image:

  4. We will now create a CustomItem class to represent carousel slide properties in the same way as the previous recipe. In the SitecoreCookbook project, create a CarouselSlide class in the Models folder and inherit it from the CustomItem class. Add Title, Image, and Url properties to it:

    public class CarouselSlide: CustomItem
    {
      public CarouselSlide(Item item)
        : base(item) { }
    
      public string Title{
        get { return InnerItem["Title"]; }
      }
    
      public HtmlString Image {
        get {
          return new HtmlString(FieldRenderer.Render(InnerItem, "Image"));
        }
      }
    
      public string Url {
        get {
          Item linkItem = Sitecore.Context.Database.GetItem(InnerItem["Link Item"]);
          if (linkItem != null)
            return LinkManager.GetItemUrl(linkItem);
          return "";
        }
      }
    }
  5. Now we will create a Controller class, which will create a list of CarouselSlide objects. In the SitecoreCookbook project, create a NavigationController controller in the Controllers folder. Create the ActionResult or ViewResult Carousel() method that will return a list of carousel items to the view:

    public class NavigationController : Controller
    {
      public ActionResult Carousel()
      {
        List<CarouselSlide> slides = new List<CarouselSlide>();
    
        MultilistField multilistField = Sitecore.Context.Item.Fields["Carousel Slides"];
        if (multilistField != null) {
          Item[] carouselItems = multilistField.GetItems();
          foreach (Item item in carouselItems) {
            slides.Add(new CarouselSlide(item));
          }
        }
        return PartialView(slides);
      }
    }
  6. Now we will register this controller and action method in Sitecore. Select the /sitecore/layout/Renderings/Cookbook item. Create a Carousel controller rendering and set the Controller and Controller Action fields, as shown in the following image:

  7. Now we will create a view to render the carousel slides. In the SitecoreCookbook project, create a Carousel.cshtml view file in the /Views /Navigation folder:

    @model IEnumerable<SitecoreCookbook.Models.CarouselSlide>
    <div class="carousel-inner" role="listbox">
      @foreach (var item in Model) {
        <div>
          <a href="@item.Url" title="@item["Title"]">
            @item.Image
          </a>
        </div>
      }
    </div>
  8. In the Main Layout file, place this rendering using the following code. Remember to update the item ID of this controller rendering in the code.

    @Html.Sitecore().Rendering("{62104CCC-D747-4671-BB3B-CFF041F42A5A}")
  9. Preview the content item; it will show carousel images on the page. Making the carousel work fully, as shown in the following image, you may need to change HTML in the view and append style sheets, which you can get from the code bundle provided with this book:

How it works…

We can render item fields using the field helper, but there is no item field available to render item URL. So, we need some custom properties to items, and that is possible by implementing custom items. A custom item is an item that has special properties and functionality that match the functionality and semantics of the item that it is associated with. Here in step 4, we created the CarouselSlide class by inheriting from the CustomItem class and also created different custom properties such as Url, Title, and Image.

Here, we also used the HtmlString (or MvcHtmlString) return type to get image, unlike Title, which has the string type. It's because we want to render HTML without encoding it what view engine does for string.

In step 4, we used the FieldRenderer.Render(<item>, <fieldName>) method to render the HTML image tag. We can also use item.Fields[].Value or item["<field>"] to get field value, but it will return raw value of the image field as shown in the following code:

<image mediaid=\"{E0A48978-2D1A-4431-8FED-BEDE851B3FD6}\" />

In step 5 and 6, we created the NavigationController class with the Carousel() action method and registered them in Sitecore. The Carousel() method prepares a list of CarouselSlide objects and pass it to the Carousel partial view, which we created in step 7.

In step 8, we placed the NavigationController rendering to the layout, so when it's invoked, it returns a ViewResult with list of CarouselSlide objects as a model and the partial view will get rendered accordingly.

If you have noticed, we registered the controller only and bound to the item and done nothing with the view. It's because, MVC finds the view itself from /Views/{Controller}/{Action}.cshtml.

See also

Sitecore also provides some other renderings such as item rendering, method rendering, and url rendering, which we will not cover in this book as they are easy to understand, rarely get used, and serve for very specific requirements. You can learn these renderings from the following links:

 

Placing renderings dynamically using placeholders


In the previous recipes, you learned placing components on a layout or view statically. You can empower the dynamic placement of components using a placeholder, which comes with lots of benefits that you will learn in this recipe.

How to do it…

We will first replace statically placed renderings with placeholders in Main Layout:

  1. We will first decide places where we can put content dynamically or we need placeholders, for example, breadcrumb, side menu, and main content area.

  2. From Main Layout, remove the existing renderings from these places and add placeholders, breadcrumb, left-colum n, and main-content as follows:

    <div class="container">
      <div id="breadcrumb">
        @Html.Sitecore().Placeholder("breadcrumb")
      </div>
      <div id="sidemenu">
        @Html.Sitecore().Placeholder("left-column")
      </div>
      <div id="contentarea">
        <article>
          @Html.Sitecore().Placeholder("main-content")
        </article>
      </div>
    </div>
  3. We already have breadcrumb and Side Menu view renderings; we will create a simple view rendering to show the Title, Body, and other fields in the main content area. In the SitecoreCookbook project, create a TitleAndBody.cshtml view file in the /Views/Content/ folder with the following content, and register this rendering:

    <h1>@Html.Sitecore().Field("Title")</h1>
    <div> @Html.Sitecore().Field("Body") </div>
  4. Now, we will place Breadcrumb, Side Menu, and Title and Body renderings in breadcrumb, left-column, and main-content placeholders accordingly. From the Content Editor, select Standard Values of the Site Root template. From the ribbon, click on the Details button in the Layout group from the Presentation tab to open the Layout Details dialog. Click on the Edit button to open the Device Details dialog and select the Controls section. It will show an empty list, but once you add renderings on placeholders, they will be displayed, as shown in the following image:

  5. To add renderings, click on the Add button from the Device Editor dialog. It will open the Select a Rendering dialog, where you can add renderings to particular placeholders, as shown in the following image:

  6. Repeat steps 4 and 5 for all template standard values, where you want to add renderings. Now, preview different pages to see the power of placeholders; you will find the renderings are displayed on the pages!

Note

We could also have used the benefit of inheriting presentation details from base templates. In Sitecore 8 onward, if you don't find your renderings inherited, you can get a bug fix for it from https://goo.gl/OSMNkR.

How it works…

A placeholder is a Sitecore component used within a layout, view, or sublayout, which allows the dynamic placement of components in it. It does not have any user interface, the same as the ASP.NET placeholder control. In Sitecore MVC, a placeholder can be created using the @Html.Sitecore().Placeholder("<placeholder name>") helper class. In Web Forms, you can use <sc:Placeholder runat="server" />.

It allows users to have design flexibility and minimize the number of layouts and renderings. For example, in this recipe, we can convert our layout from a two-column (side menu and content area) to a three-column layout, simply by adding a two-column view in the main-content placeholder. Thus, you can create any type of dynamic design just using a single layout.

When you have multiple components in a single placeholder, their order is managed by layout engine, considering the order they are added to the layout details. Their order can be changed using the Move Up and Move Down buttons in the Device Editor dialog, shown in step 4. You can remove or replace any control by clicking on the Remove or Change button.

Note

If you apply layout details to an individual item, it will override layout details defined in standard values of the data template associated with the item. To revert them to standard values, use the Reset button in the Presentation tab and Layout group from the Content Editor ribbon.

See also

You can also implement dynamic placeholders (https://goo.gl/6NIF3z).

Tip

It's also possible to use nested placeholders. When you use a view inside a view, you can set the placeholder key as /<outer placeholder key>/<inner placeholder key> to place renderings to the inner placeholder.

 

Empowering the Experience Editor using placeholder settings


Being a content owner, the Experience Editor provides a simpler user interface to change the page design. In this recipe, we will take a look at how to add components from the Experience Editor using Placeholder Settings.

Getting ready

In the previous recipe, we placed different components on different placeholders, for example, the Title and Body rendering on the main-content placeholder. We will place Carousel or any other rendering on the same placeholder from the Experience Editor.

How to do it…

As we want to place components on the main-content placeholder of the Home page from the Experience Editor, we will first create a placeholder setting for it:

  1. From the Content Editor, select the /sitecore/layout/Placeholder Settings item. Create a placeholder setting main content item in it. In its Placeholder Key field, enter the name of the placeholder that we defined in the Main Layout, for example, main-content.

  2. Now open the Home page in the Experience Editor. Find the Title and Body rendering that is placed on the main-content placeholder, as shown in the following image. From the floating toolbar visible there, click on Go to parent component to reach its parent component, which is the main-content placeholder in our case. Now, you will find two Add here buttons in the main-content placeholder to place components before and after the Title and Body rendering:

    Note

    As an alternative to this step, you can also find all the placeholder settings on the page directly. For this, from the Experience Editor ribbon, in the Home tab, in the New group, click on the Component button.

  3. Clicking on this button will open a Select a Rendering dialog, from which you can select a component to add to that place. Select the Carousel rendering to place it before the Title and Body rendering, save the changes, and see how your page has been changed!

How it works…

There are two types of placeholder settings: global placeholder settings and data template specific placeholder settings.

In the preceding steps, we used the global placeholder setting as we specified a placeholder key in the placeholder setting. So, whenever Sitecore finds the main-content placeholder in any component of the requested page, it will allow us to manage components on that placeholder. In our case, it will be shown on all the pages of the website. So ideally, it's good practice to use the global placeholder setting for placeholders of the main layout of the site.

We can also set placeholder settings on the data template level. For example, we want to restrict the main-content placeholder setting only for Site Root or other selected templates. For this, we should follow these steps:

  1. In the placeholder setting that we created, don't specify the Placeholder Key field (leave it blank) so that we can override it on the template level.

  2. Select the standard values of the Site Root template. Open its Layout Details, and select the Select the Placeholder Settings tab in the Device Details dialog. Click on the Add button, which will open the Placeholder Setting dialog. Here, select the created placeholder setting, main content, and set the main-content placeholder name, as shown in the following image, and save the settings:

Now you will be wondering how Sitecore adds the components directly to Layout Details of the page. Open the Layout Details of Home item; you will find that the Carousel rendering we added from the Experience Editor got stored to FINAL LAYOUT, where SHARED LAYOUT is still the same as before, as shown in the following image. This is because of the Versioned Layouts feature we got from Sitecore 8. Read more about it at https://goo.gl/FXxHkP:

You can also remove any components by clicking on the Remove component. button found on the floating toolbar of the component, as shown in the following image:

Learn more about the Experience Editor at https://goo.gl/1ZFIpX.

 

Restricting or swapping rendering controls on placeholders


While adding renderings from the Experience Editor, by default, it allows you to add all the renderings from the /sitecore/layout/Renderings folder. However, just imagine how difficult it would be for content owners to choose a logically valid and compatible rendering from the huge list.

In this recipe, you will learn how we can show a template-specific list of the allowed and placeholder-compatible renderings from the Experience Editor.

Getting ready

We have the main-content placeholder placed on all pages of the website. We want to restrict content authors to use Carousel, Highlight Featured Products, and Highlight News renderings only on the Home page. Similarly, for the Products landing page, we will restrict them to use Carousel and Highlight Featured Products renderings only. This recipe assumes that you have created the mentioned renderings.

How to do it…

Here, we will first override placeholder settings for the data template of the Home page:

  1. From the Content Editor, select standard values of the Site Root template. Open the Placeholder Setting dialog from the Device Editor. Remove any placeholder settings, if any. Create a new setting.

  2. Set the Name to Home Content and the Placeholder Key field to our main-content placeholder key. In the Parent field, select the main content placeholder setting that we have already created. Here, select the required renderings from the Allowed Controls field:

  3. Open the Home page in the Experience Editor. Add the renderings to it; you will find that only the preceding selected renderings will be available to pick, as shown in the following image:

  4. In the same way, you can apply these settings to standard values on Product or any other template, as per your requirement.

How it works…

Once you create this placeholder setting, you will find a new item created in the main content placeholder setting item, where you will find all the selected renderings in the Allowed Controls field:

You can also change placeholder settings from the Experience Editor by clicking on the highlighted button in the floating bar of the placeholder, as shown in the following image:

You learned how to place allowed controls on placeholders. Sitecore renderings have a Compatible Renderings field, as shown in the following image, where you can select compatible renderings to a particular rendering. So, while replacing any rendering from the Experience Editor, it will allow you to choose renderings from the selected compatible renderings only. For example, as shown in the following image, Sitecore will allow you to replace Carousel rendering with Banner rendering only. You can learn more about it at http://goo.gl/Tk5ybI:

About the Author

  • Yogesh Patel

    Yogesh Patel has been programming since the year 2000, and has been working in the IT industry for over ten years on a variety of technologies. He was mainly involved in Sitecore or .NET-based development in the Indian offices of US and UK-based organizations. He has worked at Investis Ltd as a technical architect and has lead a Sitecore development team. Yogesh has held a number of positions and has a lot of responsibilities, having worked at Investis since 2009. He has been recognized as a Most Valuable Professional (MVP) by Sitecore for 2014, 2015, and 2016.

    As a developer, Yogesh enjoys learning new programming techniques, practices, and tactics. He has worked on .NET since 2005 and Sitecore since 2009. He has also spent plenty of time developing in C, VC++, MATLAB, VB6, ASP, Java, PHP, AppleScript, SQL, and MySQL, but his current focus is on .NET—especially Sitecore. His blog can be found at http://sitecoreblog.patelyogesh.in. You can find Yogesh on Twitter at @patelyogesh_in, as well as LinkedIn (yspatel) and Facebook (patelyogesh.in).

    Browse publications by this author

Latest Reviews

(5 reviews total)
Good book to learn tips/tweaks using Sitecore
Very easy to follow. The screenshots and clear directions were useful.
In einwandfreiem Zustand. Alles Top!
Sitecore Cookbook for Developers
Unlock this book and the full library for FREE
Start free trial