Bobbler
Bobbler

Reputation: 643

MVC Razor syntax: @ followed by HTML

I came across this code today and don't really understand it. Please could someone tell me what this means and how to interpret it? I have simplified it but it's basically the @ symbol followed by some HTML.

The call is:

@Html.Tmpl(@<p>text to display</p>)

The function is:

public static HelperResult Tmpl<TModel>( this HtmlHelper<TModel> html, Func<HtmlHelper<TModel>, HelperResult> template )
{
    return new HelperResult( writer => template( html ).WriteTo( writer ) );
}

Please enlighten me. Thank you.

Upvotes: 1

Views: 862

Answers (1)

Nathan Taylor
Nathan Taylor

Reputation: 24606

This is an example of what is known as a Templated Razor Delegate. Quite simply, it is a type of HTML helper which accepts a block of Razor template code which can be used to compose the result of a complex operation.

A simple use case might be an Html.List(data, template) method which accepts a list of records and a template for each row of data. The template markup is a delegate which can be invoked and passed a model within the helper's logic.

public static HelperResult List<T>(this IEnumerable<T> items, 
  Func<T, HelperResult> template) {
    return new HelperResult(writer => {
        foreach (var item in items) {
            template(item).WriteTo(writer);
        }
    });
}

Phil Haacked goes into more detail here: http://haacked.com/archive/2011/02/27/templated-razor-delegates.aspx.

Upvotes: 2

Related Questions