In this tutorial, you will learn how to get the current page object within a Sitecore CMS-powered website. When you start building any web page within Sitecore, one of the first things that you will need to do is get information about the current page in order to render the content added by the content editors. There are a few ways of getting the current page object within Sitecore CMS. If you want to learn about all these techniques and the best practice for when you need to use each one, read on 🔥🔥🔥

How To Get The Current Page in Sitecore

There are three main techniques that I tend to use in my Sitecore projects in order to get access to the current Sitecore object. The first one I will cover is the technique I use the most, via the Sitecore.Context:

Sitecore Instance: To get information about the current item, you can use the Sitecore.Context. Sitecore.Context is a wrapper on top of the normal HttpContext. The difference between HttpContext and Sitecore.Context is that the Sitecore version exposes additional Sitecore related properties and methods. Via the Sitecore Context you can get access to the current page object:

The Sitecore.Context.Item property exposes lots of useful data about the current request. For example, if you want to know if the current page is being viewed in preview mode, or, from the website you can use this code for preview:

Or this code to check if the request is a website request:

LinkManager: Through the Sitecore.Context you can also access the LinkManager. You can use LinkManager to get the current pages Url. This is possible using this code:

Sitecore MVC Helpers: You might want to access the current page object within a Razor view. First, I would discourage you from adding logic to your views. Adding code in a view breaks the clean separation provided by MVC. A good tip to follow is to access the Sitecore object in a controller, do want you to need with it and then pass the results down via a view model. Most .NET CMS providers ship with lots of HTML helpers that allows you to perform logic within your view files. If you do not like controllers and you think writing some logic within a view is OK, the good news is that using these helpers is fairly easy. It's your project so do what makes you happy ❤️

To access the Sitecore object from within a .cshtml file, you would write this code:

Page Context: The final technique to access the Sitecore object can be used from a rendering. Using the PageContext you can access the Item property:

In the context of a rendering, the item relates to the root item that will be rendered.

You are now Sitecore current object guru 🧘. You can access this property anywhere in your codebase 💪💪💪💪. Happy Coding 🤘