Default Layout for Components

_Imports.razor will help you to set the default layout for all components inside a folder. It is used to group components that use the same layout. The layout set in _Imports.razor will override the layout set in RouteView.

You can download the example code used in this topic on GitHub.

Creating a layout

Before setting the layout for components, you need a layout first. Follow the steps described in Theming and Layouts guide to create a layout. In this example, we will use the following layout:

@inherits LayoutComponentBase

<h3>LayoutForFolder</h3>
@Body

Creating a component folder

In this step, you need to put components that are using the same layout in a same folder. This image taken from our example.

In the example, we put FirstComponentInFolder and SecondComponentInFolder component to the LayoutByFolder folder.


Creating _Imports.razor

The next step is to create a Razor component with the name _Imports.razor in the folder. You need to use the @layout directive to set the default layout for the folder.

@layout LayoutForFolder
The _Imports.razor is a special component, for this technique to work, you will need to name your component extractly _Imports.razor.
There is a _Imports.razor component at the same level of App.razor. Do not use @layout directive in this component.

BLAZOR SCHOOL
Designed and built with care by our dedicated team, with contributions from a supportive community. We strive to provide the best learning experience for our users.
Docs licensed CC-BY-SA-4.0
Copyright © 2021-2025 Blazor School
An unhandled error has occurred. Reload 🗙