Create HTML Table. render and theming | Drupal 8

Create HTML Table. render and theming

Submitted by editor on Fri, 09/30/2016 - 10:18
Question

How to create HTML Table quickly ?

Example : Table.

$header = ['#','Name', 'Mail'];
$data = [
  [1,'Name 1', 'Mail1@example.com'],
  [2,'Name N°2', 'second@example.com'],
];

$output[] = array(
  '#theme' => 'table',
  //'#cache' => ['disabled' => TRUE],
  '#caption' => 'The table caption / Title',
  '#header' => $header,
  '#rows' => $data,
);

Add a class to a Drupal table cell containing ['data'] Example:

   $header = ['#', 'Name', 'Mail'];
    $data = [
      [['data' => 2, 'class' => 'green'], 'Name 1', 'Mail1@example.com'],
      [['data' => 2, 'class' => 'red'], 'Name N°2', 'second@example.com'],
    ];

Note : To add link to a table field, You must use Drupal\Component\Render\FormattableMarkup (\Drupal\Component\Render\FormattableMarkup)
Example:
$value = new FormattableMarkup('<a href=":link">More</a>', [':link' => $url->toString()]);

Preprocessors:

template_preprocess_table(&$vars);

This Table use following twig template:

<table{{ attributes }}>
  {% if caption %}
    <caption>{{ caption }}</caption>
  {% endif %}

  {% for colgroup in colgroups %}
    {% if colgroup.cols %}
      <colgroup{{ colgroup.attributes }}>
        {% for col in colgroup.cols %}
          <col{{ col.attributes }} />
        {% endfor %}
      </colgroup>
    {% else %}
      <colgroup{{ colgroup.attributes }} />
    {% endif %}
  {% endfor %}

  {% if header %}
    <thead>
      <tr>
        {% for cell in header %}
          <{{ cell.tag }}{{ cell.attributes }}>
            {{- cell.content -}}
          </{{ cell.tag }}>
        {% endfor %}
      </tr>
    </thead>
  {% endif %}

  {% if rows %}
    <tbody>
      {% for row in rows %}
        <tr{{ row.attributes }}>
          {% for cell in row.cells %}
            <{{ cell.tag }}{{ cell.attributes }}>
              {{- cell.content -}}
            </{{ cell.tag }}>
          {% endfor %}
        </tr>
      {% endfor %}
    </tbody>
  {% elseif empty %}
    <tbody>
      <tr>
        <td colspan="{{ header_columns }}">{{ empty }}</td>
      </tr>
    </tbody>
  {% endif %}
  {% if footer %}
    <tfoot>
      {% for row in footer %}
        <tr{{ row.attributes }}>
          {% for cell in row.cells %}
            <{{ cell.tag }}{{ cell.attributes }}>
              {{- cell.content -}}
            </{{ cell.tag }}>
          {% endfor %}
        </tr>
      {% endfor %}
    </tfoot>
  {% endif %}
</table>

 

Add new comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.