Search code examples
piranha-cms

Accessing global site regions in Piranha CMS


I have added a global site region to my site and filled it with some content. How can I read this content from page view and/or layout?


Solution

  • This feature differs a bit between WebPages & MVC, the reason for this being that in WebPages (like WebForms) a Layout-page have a different model than the actual page being executed. If you use WebPages you simply add the following line first in the Layout page:

    @inherits Piranha.WebPages.LayoutPage
    

    This will automatically load the layout page model and all the global regions.

    If you're using MVC this can't be done automatically as the Layout doesn't have a model. You can simply add the following in your Layout-page:

    @{
      Piranha.Models.PageModel global;
    
      if (HttpContext.Current.Items["Piranha_CurrentPage"] != null) {
        var current = 
          (Piranha.Models.Page)HttpContext.Current.Items["Piranha_CurrentPage"];
    
        global = Piranha.Models.PageModel.GetBySite(current.SiteTreeId);
      } else {
        global = Piranha.Models.PageModel.GetBySite(Piranha.Config.SiteTreeId);
      }
    }
    

    This snippet loads the layout page from:

    1. If it's a page is displayed it loads the site tree the page is contained in
    2. If it's a post it loads the site tree from the current site.

    Hope this helps you!

    Regards

    /Håkan