Emphram Stavanger Emphram Stavanger - 1 year ago 46
PHP Question

Drupal 8 Double Field HTML

I'm using Drupal 8, and the Double Field module. I want for the second field to allow HTML tags, but currently the tags are directly output on the page as text. There is no field format that would not escape HTML tags.

In the issues for this module, the author suggests "overriding theme_double_field()", but I don't know how to go about that.

How can I enable HTML tags for the second field of a double field?

Answer Source

By default, all strings in twig templates are escaped. That's why you lose your formatting. You can avoid this in 2 ways:

  1. Use FormattableMarkup in preprocess function to pass formattable string variable to your twig template.
  2. Use raw filter in twig template.

Double Field provides several formatters, but suppose you use the simplest Unformatted list formatter, which uses double_field_item theme to render double field item.

Then the first solution is to write your own preprocess function for double_field_item theme:

use Drupal\Component\Render\FormattableMarkup;

function mytheme_preprocess_double_field_item(&$variables) {
  $item = $variables['elements']['#item'];
  $second_value = new FormattableMarkup($item->second, []);
  $variables['item']['second'] = $second_value;

And the alternative second solution is to override double-field-item.html.twig template in your theme:

{% for subfield, subitem in item %}
    {% if subitem %}
        <div class="double-field-{{ subfield }}">
            {% if settings[subfield].prefix %}
                <span class="double-field-prefix">{{ settings[subfield].prefix }}</span>
            {% endif %}
            {{ subitem|raw }}
            {% if settings[subfield].suffix %}
                <span class="double-field-suffix">{{ settings[subfield].suffix }}</span>
            {% endif %}
    {% endif %}
{% endfor %}

Choose any :)