Layouts in Blazor
Certain layout elements like menus, copyright messages, logos, etc. must be present on all pages. Copying the code of these layout elements onto all pages would not be a good solution. The app would become hard to maintain and probably inconsistent over time. Blazor Layouts solve this problem. Layout page helps us to reduce duplicate code in our application and helps us to make the look and feel consistent throughout the application. It is very similar to Layout in ASP.net MVC application. Blazor also supports nested layout.
Lets add bootstrap components in our layout
We will add bootstrap to our project by adding the bootstrap CDN betwen the header tags in the index.html in the /wwwroot folder. Blazor use a modified version of bootstrap, by adding the official bootstrap CDN we will be able to use the official bootstrap documentation.
Remember to comment out Blazor default bootstrap css!
What makes a Layout?
Layouts are technically another Blazor component. A layout is defined in a Razor template or in C# code and can contain data binding, dependency injection, and other ordinary features of components. Two additional aspects turn a component into a layout:
- The layout component must inherit from BlazorLayoutComponent. BlazorLayoutComponent defines a Body property that contains the content to be rendered inside the layout.
- The layout component uses the Body property to specify where the body content should be rendered using the Razor syntax @Body. During rendering, @Body is replaced by the content of the layout.
Create a Razor View file in the ‘Shared’ folder, we will name the file AppLayout.cshtml. The following code sample shows the Razor template of a layout component. Note the use of BlazorLayoutComponent and @Body:
The <NavBarMenu> tags are a custom navbar component in the ‘shared’ folder
- Using @layout directive or Layout attribute
- Define layout globally
The ‘_ViewImports.cshtml’ file was introduced in ASP.net MVC and it provides a mechanism to make directives available to Razor pages globally so that we aren’t required to add them to pages individually. We can also use this file to define Layout page in Blazor. If we define Layout page in this file, Layout is automatically applied to all the Blazor pages in the folder heirarchy.
We can also define the namespaces that are used in all the views in a folder to _viewImports.cshtml file.
Let’s run the project
We now have created a layout to render our application components and got bootstrap running inside. We have created a base for our application to start from scratch.
Here is a gif of the project running
Now that you know how to create and use layouts, you can take advantage of this and design faster and better-looking web applications.