Structured Rich text rendering

Petr Švihlík edited this page Sep 27, 2018 · 10 revisions

Introduction

This information applies to Rich text model properties typed as IRichTextContent. In case you are using string data model, see String-based rendering of linked items in Rich text.

You can influence which approach to use by applying the --structuredmodel parameter during model generation.

Structured Rich text data model

IRichTextContent provides a list of blocks of one of the following types:

  • IInlineImage
  • IHtmlContent
  • IInlineContentItem

By iterating over the blocks, you can render the Rich text content.

Rich text rendering in MVC

For rendering of rich text in MVC, you can use the standard approach with Html.DisplayFor(model => model.RichTextProperty).

Individual blocks are rendered with their default HTML representation which matches the content provided by the Delivery API.

You can provide display templates for the following block types:

  • Linked items (required) - Display template named <ModelTypeName>.cshtml where model type name is based on the linked item type, e.g. Tweet.cshtml
  • Inline images (optional) - Display template named InlineImage.cshtml

Display templates can be provided to all MVC Controllers through the Shared folder, or relatively based on the current controller.

Example

Models/ContentTypes/Article.cs - Generated

    public partial class Article
    {
...
        public IRichTextContent BodyCopy { get; set; }
...
    }

Views/Articles/Show.cshtml

    <div class="row">
        <div class="article-detail-content">
            @Html.DisplayFor(vm => vm.BodyCopy)
        </div>
    </div>

Views/Articles/DisplayTemplates/HostedVideo.cshtml

@model DancingGoat.Models.HostedVideo

@{ 
    var host = Model.VideoHost.FirstOrDefault()?.Codename;
    if (host == "vimeo") {
        <iframe class="hosted-video__wrapper"
                src="https://player.vimeo.com/video/@(Model.VideoId)?title =0&byline =0&portrait =0"
                width="640"
                height="360"
                frameborder="0"
                webkitallowfullscreen
                mozallowfullscreen
                allowfullscreen
                >
        </iframe>
    }
    else if (host == "youtube") {
        <iframe class="hosted-video__wrapper"
                width="560"
                height="315"
                src="https://www.youtube.com/embed/@(Model.VideoId)"
                frameborder="0"
                allowfullscreen
                >
        </iframe>
    }
}

Analytics

You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Press h to open a hovercard with more details.