blazorblazor-server-side

Blazor page elements other than Body


I have a Blazor server-side app, trying to understand the structure. Inside the MainLayout.razor page, I see the tag @Body, and this is where each page's content is rendered.

I am wondering, is it possible to add additional render element to the mainLayout page? For example, a @Header section. And I would prefer to define this section inside each individual page as well.

In other words, for each page, besides the main content, it also needs to define Header, Footer, or whatever render element I define in the MainLayout. This way, I can have customize Header/Footer elements that are unique for each page.

Thanks for any help.


Solution

  • MainLayout.razor

    Note: The use of a method to update the render fragment fields I deliberately made private which then calls StateHasChanged(). Other methods could easily be created to clear or set other fields.

    @inherits LayoutComponentBase
    
    <CascadingValue Value="this">
        <div class="page">
            <div class="sidebar">
                <NavMenu />
            </div>
            <div class="main">
                <div class="top-row px-4">
                    @header
                </div>
    
                <div class="content px-4">
                    @Body
                    @footer
                </div>
            </div>
        </div>
    </CascadingValue>
    
    @code {
        private RenderFragment header;
        private RenderFragment footer;
    
        public void SetHeaderAndFooter(RenderFragment header, RenderFragment footer)
        {
            this.header = header;
            this.footer = footer;
            StateHasChanged();
        }
    }
    
    

    LayoutSetter.cs

    
    public class LayoutSetter : ComponentBase
    {
        [CascadingParameter]
        public MainLayout Layout { get; set; }
    
        [Parameter]
        public RenderFragment Header { get; set; }
    
        [Parameter]
        public RenderFragment Footer { get; set; }
    
        protected override void OnInitialized()
        {
            Layout.SetHeaderAndFooter(Header, Footer);
        }
    }
    
    

    On any page...

    @page "/"
    
    <h1>Hello, world!</h1>
    
    <LayoutSetter>
        <Header>
            Hello
        </Header>
        <Footer>
            Goodbye
        </Footer>
    </LayoutSetter>