Score:2

How to get the description text from metatag field

jp flag

A content type in my Drupal 9 instance uses the Metatag module. I want to extract the 'description' metatag value and include it in a twig template (for the node).

But when I look at the variables available, it looks like field_metatag contains PHP serialize()-ed code.

I want to do something like

<div class="the-description">
  {{ node.field_metatag.description|e('html') }}
</div>
Score:3
ne flag

You can get the serialized data via node.field_metatag.value.

But seems there's no ready-made unserialize Filter for Twig. And the tags are hidden from the node because they are supposed to be used on page-level instead. So you either write an unserialize filter yourself or preprocess the description into the template.

I found the following preprocess to be working.

/**
 * Implements template_preprocess_node().
 */
function MYTHEME_preprocess_node(&$variables) {
  $node = $variables['node'];

  $tags = \Drupal::service('metatag.manager')
    ->tagsFromEntityWithDefaults($node);

  if (!empty($tags['description'])) {

    $description = \Drupal::service('metatag.token')
      ->replace($tags['description'], ['node' => $node]);

    $variables['my_description'] = strip_tags($description);
  }
}
{% if my_description %}
  {{ my_description }}
{% endif %}

Sauce: https://imalabya.co/fetch-metatags-programmatically-drupal

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.