Introduction
Blazor by default comes with layouts that are shared across various components, but there are times when building an application you need to have different layouts for various pages, this article will demonstrate how to go about this.
Step 1-Create a new layout
Right-click Shared Folder, go to Add, then chose Razor Component.
In this situation, I want to ensure no sidebar navigation menu exists on the login page, so I will give the component a meaningful name like EmptyLayout, file extension is .razor.
Next will create the new layout page
First, we add the below code, this is to make the layout razor component take all the attributes of a layout component.
@inherits LayoutComponentBase
Next the below code, is to let this layout apply to pages
<div class="page">
Let's quickly go to the C# code section of the page, we will come back to the HTML part later. We will create a boolean variable, and instantiate it to a value. So in the below code, a boolean variable called show is created and the value of false is given to it. So the way this works is that we can anywhere in the HTML section of the page create a div and hide all controls, components, etc inside the div class.
@code{
bool show = false;
}
Next thing is that we don't want the default sidebar navigation menu to show in this layout, we write the following in the HTML section of the page. The navigation menu component is added by using <NavMenu/>, this is the common way to refer to place components inside other components or pages.
@if (show)
{
<div class="sidebar">
<NavMenu />
</div>
}
We have now created a new layout that will hide the sidebar navigation menu. We now need to force the login page to use the new layout called EmptyLayout instead of the default Layout(MainLayout). To do this we will add the following code to the HTML section of the login page. It's advisable you place the code after the namespaces inheritances or injections.
@layout EmptyLayout
Full EmptyLayout code is below,
@inherits LayoutComponentBase
<div class="page">
@if (show)
{
<div class="sidebar">
<NavMenu />
</div>
}
<div class="main">
<div class="top-row px-4 auth">
<LoginDisplay />
<a href="" target="_blank">About</a>
</div>
<div class="content px-4">
@Body
</div>
@code{
bool show = false;
protected override void OnInitialized()
{
}
}
</div>
</div>
Final outcome- Login page with EmptyLayout
Final outcome- Other page with MainLayout(i.e the default layout with sidebar navigation menu)
Conclusion
This technique can be used in the following scenarios,
- Creation of a different layout for the Login Page.
- Creation of different layouts for different categories of users.