Skip to content

Instantly share code, notes, and snippets.

@reidev275
Last active September 4, 2016 16:04
Show Gist options
  • Save reidev275/24de58b38afbe3b206f9e9e363b61afc to your computer and use it in GitHub Desktop.
Save reidev275/24de58b38afbe3b206f9e9e363b61afc to your computer and use it in GitHub Desktop.
Helpers for dealing with Razor in a more functional way.

I ❤️ higher order functions and generally refuse to write non recursive looping structures. With Razor though I didn't have a great way of displaying lists without looping.

###Usage

The following code will render the _link partial for every item in the links list. It is basically a functor from data to output given a template.

@Html.RenderPartials("_link", links)

Without this extension I would have to write something like this

@foreach(var link in links)
{
  Html.RenderPartial("_link", link)
}

###Wrapping the partial

In the first example we're using the _link template as is. But what if we want an html list of links? This allows us to add any arbitrary html before and after each element.

<ol>
@Html.RenderPartials("_link", link, "<li>", "</li>")
</ol>

Without this extension I would have to write something like this

<ol>
@foreach(var link in links)
{
  <li>
    @Html.RenderPartial("_link", link)
  </li>
}
</ol>

###Then? Coming from languages that allow you to pipe data through functions this is essentially how I think about building software. Variables and null are the root of most evil and debugging. Using Then allows me to remove most of the variables from my code. Plus, it's a higher order function and we've already discussed my ❤️ for them :D

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Html;
namespace ViewHelpers
{
public static class HtmlExtensions
{
public static IHtmlString RenderPartials(this HtmlHelper html, string partial, IEnumerable<object> items)
{
return html.RenderPartials(partial, items, String.Empty, String.Empty);
}
public static IHtmlString RenderPartials(this HtmlHelper html, string partial, IEnumerable<object> items, string prepend, string append)
{
return items.Select(x => prepend + html.Partial(partial, x).ToString() + append)
.Then(x => String.Join("", x))
.Then(x => new HtmlString(x));
}
public static B Then<A, B>(this A obj, Func<A, B> f)
{
return f(obj);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment