Menu

Display Umbraco Tags on Razor Templates

February 12, 2015 by Christopher Sherman

Umbraco has a built-in tag data type that allows users to easily apply a list of tags to a document. But once you’ve added a tag property to a document type, how do you display the tag list in a Razor view? I’ll show you how in three steps.

In Umbraco back office, select Settings on the main menu and, in the Partial Views folder, create a new Partial View named ContentItemTags.

In the template field of the new view, use the code below to the grab tags assigned to a node and display them on the page. I’m using Font Awesome to display a tag icon font rather than a bullet point, but you can just as readily use a generic unordered list. Note that I’ve named my tag property articleTags, so you’ll either need to create a property with the same alias or change the code to match the alias of your property.

@inherits Umbraco.Web.Mvc.UmbracoTemplatePage

@if (Model.Content.HasValue("articleTags"))
{
var tagList = Umbraco.Field("articleTags").ToHtmlString().Split(',');

    <div class="title-panel">
        <h3>
            Tags
        </h3>
    </div>
    <div class="latest-updates">
        <div>
            <ul class="fa-ul">
                @foreach (var tag in tagList)
                {
                    <li>
                        <i class="fa-li fa fa-tag"></i>
                        <a href="/tags?tag=@tag" title="Get content tagged with @tag">
                            @tag
                        </a>
                    </li>
                }
            </ul>
        </div>

        <div>
            <ul class="fa-ul">
                <li>
                    <i class="fa-li fa fa-tags"></i>
                    <a href="/tags" title="View tagged content">
                        Browse tags
                    </a>
                </li>
            </ul>
        </div>
    </div>

}

In the template folder, open the template on which you want to render the tag list and use the HTML helper function below. This helper renders the partial view, caching it by page for one day.

@Html.CachedPartial("ContentItemTags", Model.Content, 86400000, cacheByPage: true)

Umbraco Razor