How do layouts work in Blazor, and what are the roles of @layout, LayoutComponentBase, and the @Body placeholder?
Last updated
Layouts let you define shared shell markup (nav, header, footer) once and wrap page content inside it: a layout is a component that inherits LayoutComponentBase and renders its page via @Body, while pages opt in with @layout.
LayoutComponentBase: The base class every layout inherits; it supplies aBodyparameter of typeRenderFragment.@Body: The placeholder in the layout markup where the routed page's content is rendered.@layout: A directive placed in a page (or in_Imports.razorfor a whole folder) to select which layout wraps it.Applying layouts globally: The
Router'sRouteViewtakes aDefaultLayout, so pages without an explicit@layoutstill get one.Nesting: A layout can itself declare
@layoutto nest inside another layout.
[lang:razor]
@* MainLayout.razor *@
@inherits LayoutComponentBase
<nav>...</nav>
<main>@Body</main>
@* SomePage.razor *@
@page "/some"
@layout MainLayout
- https://www.telerik.com/blogs/blazor-basics-working-blazor-layouts
- https://chrissainty.com/blazor-bites-layouts/
- https://learn.microsoft.com/en-us/aspnet/core/blazor/components/layouts?view=aspnetcore-10.0
- https://www.learnblazor.com/layouts
- https://www.luisllamas.es/en/blazor-layouts-master-templates/
- https://blazor-university.com/layouts/nested-layouts/