Live Chat Icon For mobile
Live Chat Icon

Blazor FAQ - Layouts

Find answers for the most frequently asked questions
Expand All Collapse All

Technically, a layout is just another component.

To convert a component into a layout it:

  • Inherits from LayoutComponentBase, which adds the Body property to the layout.
  • Uses the Razor syntax @Body in the markup where the content should need to be rendered.

The default template of Blazor contains MainLayout.cshtml under the shared folder. It works as a layout page.

@inherits LayoutComponentBase

<div class="sidebar">
    <NavMenu />
</div>

<div class="main">
    <div class="content px-4">
        @Body
    </div>
</div>

Use layout in component

The layout can be defined by using both @layout directive and Layout Attribute in a component.

Using @layout directive

[Layout(typeof(MainLayout))]
public class BaseComponent : ComponentBase
{
    public string text { get; set; } =
       "Hello!";
}

Define Layout globally

The layout can be defined globally for all component. So that there is no need to add them each page.

In _import.cshtml file, import the MainLayout.

@layout MainLayout
@using Microsoft.AspNetCore.Components

Reference link :

https://www.c-sharpcorner.com/article/working-with-layout-page-in-blazor/

Permalink

Share with

Couldn't find the FAQs you're looking for?

Please submit your question and answer.