DLeh
DLeh

Reputation: 24395

Razor Optionally Wrap output

I have some html that I want to wrap with another tag optionally.

For instance, this would be an unread document:

<strong>
    <a href="viewDocument">
        View Document
    </a>
</strong>

And this would be a read document:

<a href="viewDocument">
    View Document
</a>

Is there an easier way to do this besides adding two @if Statements like so? This way is a bit clunky

@if(test)
{
    @:<strong>
}
    <a href="viewDocument">
        View Document
    </a>
@if(test)
{
    @:</strong>
}

Upvotes: 0

Views: 149

Answers (1)

DLeh
DLeh

Reputation: 24395

Based off of this answer I adapted an optional wrapping HtmlHelper that I thought would be useful for others. This will wrap the html only if the provided test evaluates to true.

In your static class for Html Helpers:

public static IDisposable BeginOptionalWrap(this HtmlHelper helper, string tag, bool test, object htmlAttributes = null)
{
    var tb = new TagBuilder(tag);
    var attrs = GetAttributes(htmlAttributes);
    if (attrs != null)
    {
        tb.MergeAttributes(attrs);
    }
    if (test)
    {
        helper.ViewContext.Writer.Write(tb.ToString(TagRenderMode.StartTag));
    }

    return new OptionalWrap(helper, tb, test);
}

The class:

public class OptionalWrap : IDisposable
{
    private readonly HtmlHelper _Helper;
    private readonly TagBuilder _Tag;
    private readonly bool _test;

    public OptionalWrap(HtmlHelper helper, TagBuilder tag, bool test)
    {
        _Helper = helper;
        _Tag = tag;
        _test = test;
    }

    public void Dispose()
    {
        if (_test)
        {
            _Helper.ViewContext.Writer.Write(_Tag.ToString(TagRenderMode.EndTag));
        }
    }
}

Usage:

@using(Html.BeginOptionalWrap("strong", Model.IsUnread, new { @class="someClass" })){
    <a href="viewDocument">
        View Document
    </a>
}

Upvotes: 1

Related Questions