In this tutorial, you will learn how to check if the current page request is the Sitecore homepage object. You will learn about the different Sitecore API's that you can use to achieve this goal. For example, which technique should you use in a single-language site compared to a multi-language site? If this knowledge sounds of use to you, read on 🔥🔥🔥
How To Configure The Sitecore Homepage Item
Before we begin, it will be useful for you to know how to set the homepage object within Sitecore. The homepage object is set within your website web.config
file. You will need to configure this value when setting up your website. To check what values your site is using, open your web
config` and navigate to the 'sites' section. You should see the following entry:
From this configuration, the startItem
property defines which item the GetItem()
call will return.
By Url: The easy way to check if the current request has been generated from the homepage is by the Url. If the current Url and the Homepage Url match, you are onto a winner 🏁🏁🏁
On Line1, we use the Sitecore.Context.Database.GetItem()
method to get the homepage item. With the homepage object, you can compare the homepage ID with the current page ID. If the two matches, the job is a good one 💥
An alternative way of comparing is on thepath
property:
By Template Type: An alternative option is to check if the current item is using the homepage template. This approach can be handy in a multi-language scenario. On some projects, you might have more than one homepage. In these scenarios comparing by ID alone will not work. Comparing on template type will match on multiple pages rather than one. You can compare templates in one of two ways. First, using the TemplateName
property:
You can also make a comparison by TemplateID
:
Potential Red Flags 🚩🚩🚩
When comparing by template ID, one thing to keep in mind is the differences between environments. On some projects, it is not uncommon for editors to manually re-created the content created in development within production. If this is how you copy content between environments, the homepage template ID will differ.
Fixing the issue is simple enough. You will need to add the value within appSettings
within your web.config
. Use build transforms to ensure the correct value is used on deployment. I would not avoid using the template name, as it is very easy to rename something in the editor which would break your site 🤔
You now know about the different ways to check if the current page request is the home page. If you only have a single language site, I would recommend comparing the homepage ID against the current item ID as the safest and easiest approach. If you are working in a multi-language environment, I suggest you use template comparison as it gives you a bit more flexibility. Happy Coding 🤘