Render Plain text field type as HTML

Last updated on 17/11/2017

To render a plain text without encoding the HTML tags you'll have to create a new Field Formatter

 

Create a file on "mymodule/src/Plugin/Field/FieldFormatter/PlainTextHTMLFormatter.php"

<?php
namespace Drupal\mymodule\Plugin\Field\FieldFormatter;
 
use Drupal\Core\Field\FormatterBase;
use Drupal\Core\Field\FieldItemListInterface;
 
/**
 * Plugin implementation of the 'plain_text_html' formatter.
 *
 * @FieldFormatter(
 *   id = "plain_text_html",
 *   label = @Translation("Plain text to HTML"),
 *   field_types = {
 *     "string",
 *     "string_long",
 *   },
 * )
 */
class PlainTextHTMLFormatter extends FormatterBase {
 
  /**
   * {@inheritdoc}
   */
  public function viewElements(FieldItemListInterface $items, $langcode) {
    $elements = [];
 
    foreach ($items as $delta => $item) {
      $elements[$delta] = [
        '#type' => 'inline_template',
        '#template' => '{{ value|raw }}',
        '#context' => ['value' => $item->value],
      ];
    }
 
    return $elements;
  }
}