1

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.

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Just when I thought I was beginning to understand functional programming :) I'll study this until I get it but for now I need to know how I would pass the @<p>text to display</p> into a Partial view so that I can call @Html.Tmpl within the Partial. Thanks again.
For anyone that's interested, the answer to my previous comment is make the Partial model a HelperResult and render it in the View with @Html.Partial("_ThePartial", Html.Tmpl(@<p>text to display</p>)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.