Search code examples
c#blazor

Blazor: Determine Layout based upon Route


Is it possible to do something like this:

<Router AppAssembly="@typeof(Routes).Assembly">
    <Found Context="routeData">
        <RouteView RouteData="@routeData" Path="/admin/*" DefaultLayout="@typeof(AdminLayout)" />
        <RouteView RouteData="@routeData" Path="/user/*" DefaultLayout="@typeof(UserLayout)" />
        <FocusOnNavigate RouteData="@routeData" Selector="h1"/>
    </Found>
</Router>

I've found this question: Change layout in Blazor page based on URL

But it doesn't quite do what I want with multiple layout files. Thanks.


Solution

  • The easiest way is to set your layout in the _imports.razor file:

    Simply structure your pages in folders:

    • Pages

      • Folder1
        • _imports.razor <= add the line @layout Folder1Layout
        • Page11.razor
        • Page12.razor
      • Folder2
        • _imports.razor <= add the line @layout Folder2Layout
        • Page21.razor
        • Page22.razor
        • Folder21
          • _imports.razor <= add the line @layout Folder21Layout
          • Page211.razor
    • Layouts

      • Folder1Layout.razor
      • Folder2Layout.razor
      • Folder21Layout.razor

    You can add also any attributes you want in the _imports.razor to apply them to the pages in the same folder. For example for pages to manage user account, you want the user with authorizations:

    @layout ManageLayout
    @attribute [Microsoft.AspNetCore.Authorization.Authorize]
    

    In your case, Folder1 can be admin and Folder2 user