How to truncate the node title in Drupal?

Option 1:

We can handle it in hook_preprocess_node() in THEMENAME.theme

/**
 * Implements template_preprocess_node().
 */
function THEMENAME_preprocess_node(&$variables) {

  $node = $variables['node'];
  $title = $node->getTitle();
  $variables['node_title'] = $title;
  if($title) {
    if(strlen($title) > 66) {
      $title_array = explode(" ", $title);
      $title_word_count = 0;
      $trim = [];

      foreach($title_array as $ta) {
        $word_count = strlen($ta);
        if($title_word_count < 66) {
          $title_word_count = $title_word_count + $word_count;
          $trim[] = $ta;
        }
      }
      $variables['node_title'] = implode(" ", $trim)."...";
    } 
  }
}

Print the variable in the node.html.twig file or your custom node twig file.

{{ node_title }}

 

Option 2:

We can handle it directly via twig file

In Twig:

{% if node.label|length > 60 %}
  {% set title_array = node.label|split(' ') %}
  {% set title_word_count = 0 %}
  {% for ta in title_array %}
      {% set word_count = ta|length %}
      {% if title_word_count > 60 %}
        {% set title_word_count = title_word_count + word_count %}
        {{ ta }} 
      {% endif %}
  {% endfor %}...
{% else %}
  {{ node.label }}
{% endif %}

 

That's it.

Enjoy! :)

Add new comment

Restricted HTML

  • Allowed HTML tags: <a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.
1 + 1 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.