I want to have more flexibility in creating content as usual. Therefore, I use the Paragraphs module, and I also disabled the standard body text. So now, a user can now freely decide how he wants to mix images, text and other content (like embedded videos). For example, an article could now start with a text followed by a full size image, or with 2 half size images followed by a full size video and then the text and so on.
So far so good. Now the problem is that I loose the standard summary function since the default body text is just disabled. This is especially a problem for any list of articles, i.e. the front page.
I have managed to kinda solve this problem by a custom preprocess hook:
function MY_THEME_preprocess_node(array &$variables) {
$node = \Drupal\node\Entity\Node::load($variables['node']->id());
if ($node->field_paragraph && !empty($node->field_paragraph->getValue())) {
foreach ($node->field_paragraph->getValue() as $key => $value) {
$paragraph = FALSE;
if (!empty($value['entity'])) {
// Use that, we're probably previewing.
$paragraph = $value['entity'];
} elseif (!empty($value['target_id'])) {
$paragraph = Paragraph::load($value['target_id']);
}
if (!empty($paragraph) && $paragraph instanceof Paragraph) {
$summary = $paragraph->getSummary();
if ($summary && $paragraph->type->getValue()[0]["target_id"] === "text") {
$variables['summary'] = $summary;
break;
}
}
}
}
}
What this does is to loop over all paragraph entries (if any) in a given node and stop iterating at the first occurence of a paragraph type named "text", if there is also a result for the getSummary()
function, i.e. this paragraph item also contains some text. Keep in mind that I am far from being a Drupal expert, so this code might not be the optimal way?
However, I cannot seem to control the length of the summary, also any headlines defined in the same paragraph are included as well. Last but not least, the result also contains unneeded markup, so in my node--article--teaser.html.twig
twig template I have to strip out those tags again:
<p>{{ summary|striptags }}</p>
The next problem arises when I want to use that summary for the description meta tags on any given article page (so in this case, NOT the pages that contain only lists of articles). Usually I would just use the Metatags module and use this for the description: [node:summary]
Of course that does not work here, and I can imagine that further down the road I will encounter more problems like this.
Therefore, it seems to me that the cleanest way would be to kinda emulate [node:summary]
, i.e. that this value is automatically calculated by something similar to the function I used above. So for the consumer of this value this would look identical as if the page / node had an actual "default" summary.
Now, is this possible at all, and if "yes" how can I achieve this? Any insights are greatly appreciated!