Razor Slices support layouts through a specific inheritance and implementation pattern.
1. Define the Layout
Inherit from RazorLayoutSlice or RazorLayoutSlice<TModel> and use @await RenderBodyAsync() to define where the content goes. You can also use @await RenderSectionAsync("SectionName") to define sections.
@inherits RazorLayoutSlice<LayoutModel>
<!DOCTYPE html>
<html lang="en">
<head>
<title>@Model.Title</title>
@await RenderSectionAsync("head")
</head>
<body>
@await RenderBodyAsync()
<footer>
@await RenderSectionAsync("footer")
</footer>
</body>
</html>
2. Implement the Slice using the Layout
To use a layout, implement IUsesLayout<TLayout> or IUsesLayout<TLayout, TModel>. If the layout requires a model, you must implement the LayoutModel property in the slice's @functions block.
@inherits RazorSlice<SomeModel>
@implements IUsesLayout<LayoutSlice, LayoutModel>
<div>
@* Content here *@
</div>
@functions {
public LayoutModel LayoutModel => new() { Title = "My Layout" };
}
3. Overriding Sections
Slices can provide content for layout sections by overriding ExecuteSectionAsync:
protected override Task ExecuteSectionAsync(string name)
{
if (name == "lorem-header")
{
<p>Custom section content.</p>
}
return Task.CompletedTask;
}
Note: The standard Razor @section directive is not supported.
@inherits RazorSlice<SomeModel>
@implements IUsesLayout<LayoutSlice, LayoutModel>
@functions {
public LayoutModel LayoutModel => new() { Title = "My Layout" };
}