Page Layouts vs. Body id revisited and solved


Right after I posted my last article on using Page Layouts for dynamic body ids and issues that you stumble on, I got one more idea on how you might leverage Page Layouts for setting dynamic body ids and still deliver a great performing solution.

In my last post I discussed how accessing the PublishingPage.Layout property requires you to login, which makes it very inconvenient when working with Internet-facing websites. Elevating Privileges allows you to work around this issue but it introduces a performance penalty that isn’t really worth it. There is however one more thing that you should try before giving up on Page Layouts…

Before I explain you anything more let’s have a look at sample code:

if (SPContext.Current != null &&
    SPContext.Current.ListItem != null)
{
    try
    {
        string pageLayout = SPContext.Current.ListItem["PublishingPageLayout"] as string;
        if (!String.IsNullOrEmpty(pageLayout))
        {
            SPFieldUrlValue pageLayoutUrl = new SPFieldUrlValue(pageLayout);
            string pageLayoutName = Path.GetFileName(pageLayoutUrl.Url);
            // set body id based on the name of the Page Layout
        }
    }
    catch (Exception)
    {
        // exception handling goes here
    }
}

While looking at the PublishingPage.Layout property I totally forgot about the PublishingPageLayout column that contains the link to the Page Layout used by the Publishing Page. This value can be then wrapped in the SPFieldUrlValue object and from there it’s straight-forward. The best part of this approach is, that it uses information available in the current context and doesn’t require you to elevate privileges or open new instances of SPSite/SPWeb.

Page Layouts for body ids? Definitely!

Technorati Tags: SharePoint,WCM

Others found also helpful: