How to reuse HTML snippets INSIDE a cshtml view in ASP.NET Core MVC?

I have a file called TopBar.cshtml:

<nav class="white" role="navigation">
    <div class="nav-wrapper container">
        <a id="logo-container" href="#" class="brand-logo">Logo</a>
        <ul class="left hide-on-med-and-down">
            <li><a href="#">Navbar Link</a></li>
        </ul>
        <ul id="nav-mobile" class="sidenav">
            <li><a href="#">Navbar Link</a></li>
        </ul>
        <a href="#" data-target="nav-mobile" class="sidenav-trigger"><i class="material-icons">menu</i></a>
    </div>
</nav>

As you can see, there are two identical sections defined for menu items. One for larger screens and one for smaller ones. In ASP.NET MVC I could do this:

<nav class="white" role="navigation">
    <div class="nav-wrapper container">
        <a id="logo-container" href="#" class="brand-logo">Logo</a>
        <ul class="left hide-on-med-and-down">
            @Menu()
        </ul>
        <ul id="nav-mobile" class="sidenav">
            @Menu()
        </ul>
        <a href="#" data-target="nav-mobile" class="sidenav-trigger"><i class="material-icons">menu</i></a>
    </div>
</nav>

@helper Menu() {
    <li><a href="#">Navbar Link</a></li>
}

In other words, I could use @helper to get HTML reusage INSIDE one and only one view.

However, as much as I know this is removed in ASP.NET Core MVC. What can I do to get to the same result?

Upvotes: 2

Views: 1298

Answers (1)

Anuraj
Anuraj

Reputation: 19618

You can do something like this.

@{
   Func<System.Collections.Generic.IEnumerable<string>, Microsoft.AspNetCore.Html.IHtmlContent> Menu = @<ul>
   @foreach (var menuEntry in item)
   {
       <li><a href="@menuEntry">@menuEntry</a></li>
   }
   </ul>;
}

And you can use the menu function like this.

@Menu(new[]{"Home","About"})

https://github.com/aspnet/Razor/issues/715#issuecomment-299342376 - It is mentioned here that, ASP.NET Team don't have any plans to do the @helper implementation.

Upvotes: 2

Related Questions