How to dynamically switch PageLayout and MasterPage of SharePoint Publishing page?

后端 未结 6 2149
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-23 07:58

To improve both the editing and displaying experience of SharePoint WCM Publishing pages I would like to be able to switch to a special set of Masterpage/PageLayout when in edit

6条回答
  •  半阙折子戏
    2021-01-23 08:29

    I once wrote a feature to switch page-layouts depending on different criteria. The difference was, that the page-layout was changed during site-creation, not in view or edit mode. The code to change the page-layout is as follows:

        private void SetPageLayout(SPWeb web, string pageName, string pageLayoutName)
        {
            PageLayout layout = null;
            PublishingPage page = null;
            SPFile pageFile = null;
            bool checkedOut = false;
    
            try
            {
                PublishingWeb publishWeb = PublishingWeb.GetPublishingWeb(web);
                // verify that the requested pageLayout is available
                foreach (PageLayout pl in publishWeb.GetAvailablePageLayouts())
                {
                    if (pl.Name.Equals(pageLayoutName, StringComparison.OrdinalIgnoreCase))
                    {
                        layout = pl;
                        break;
                    }
                }
                // got my layout
                if (layout != null)
                {
                    page = null;
                    foreach (PublishingPage pubPage in publishWeb.GetPublishingPages())
                    {
                        if (pageName == pubPage.Name)
                        {
                            page = pubPage;
                            break;
                        }
                    }
                    // got my page
                    if (page != null)
                    {
                        pageFile = page.ListItem.File;
    
                        page.CheckOut();
                        checkedOut = true;
    
                        page.Layout = layout;
                        page.Update();
    
                        page.CheckIn("changed the page-layout to " + pageLayoutName);
                        checkedOut = false;
    
                        pageFile.Publish("");
                        // If required, approve the page
                        try
                        {
                            pageFile.Approve(string.Empty);
                        }
                        catch
                        {
                            // Page doesn't need to be approved
                        }
                    }
                }
            }
    

提交回复
热议问题