Guerrilla
Guerrilla

Reputation: 14846

Insert html linebreak in view output

I have a field in the database that has linebreaks in it. I want to see the linebreaks in my view so I made this display template:

~/Views/Shared/DisplayTemplates/_StringWithBreaks.cshtml

@model string

@( Model.Replace(System.Environment.NewLine, "<br>") )

And then I call it like:

@Html.DisplayFor(modelItem => item.BodyTemplate, "_StringWithBreaks" )

The problem is it escapes the HTML so instead of inserting in the HTML it escapes it so the <br> is readable.

What is the proper way to do this so breaks appear?

Upvotes: 1

Views: 50

Answers (1)

user3559349
user3559349

Reputation:

You can just style the containing element with white-space: pre (a DisplayTemplate is not really necessary for this)

<div style="white-space: pre;">
    @Html.DisplayFor(modelItem => item.BodyTemplate)
</div>

css whitespace reference

Upvotes: 1

Related Questions