D
D
Dmitry Shnyrev2021-01-12 11:16:29
ASP.NET
Dmitry Shnyrev, 2021-01-12 11:16:29

How to properly convert Text to HTML in Aps.Net?

Tell me the equivalent in ASP.NET of this wonderful feature from RoR
https://apidock.com/rails/ActionView/Helpers/TextH...
I need to translate plain text into beautiful HTML. Not just replace the newline with <br/>, but something more serious. Maybe there are some third parties?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vasily Bannikov, 2021-01-12
@dmnBrest


Returns text transformed into HTML using simple formatting rules. Two or more consecutive newlines(\n\n or \r\n\r\n) are considered a paragraph and wrapped in tags. One newline (\n or \r\n) is considered a linebreak and a
You can pass any HTML attributes into html_options. These will be added to all created paragraphs.
Options
:sanitize - If false, does not sanitize text.
:wrapper_tag - String representing the wrapper tag, defaults to "p"

I have never seen this in particular.
In principle, it is not difficult to ride a bike like this.
A bike

static string ToHtml(string text, bool sanitize = true, string? wrap = null)
{
  var normalized = text.Replace("\r\n", "\n");
  if (sanitize)
    normalized = WebUtility.HtmlEncode(normalized);
  var paragraphs = text.Split("\n\n")
    .Select(paragraph =>
    {
      var lines = paragraph.Split("\n");
      return string.Join("\n<br/>", lines);
    });
  var htmlText = string.Join("\n\n", paragraphs.Select(p => $"<p>\n{p}\n</p>"));
  return wrap != null 
    ? $"<{wrap}>\n{htmlText}\n</{wrap}>" 
    : htmlText;
}


If you need more complex formatting, then there is one for working with markdown: https://github.com/xoofx/markdig

V
Victor P., 2021-01-12
@Jeer

Hello, can you elaborate on what tasks this is used for? Some example.
Is the text written in some editor? Why then some strange custom substitutions? There are wysiwyg or some tinymce editors that immediately produce html output.
That is, here the text is transmitted and in separate parameters, what should this text be wrapped in or a type of that?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question