How to get Node contents #995
-
|
Hello! I need to get the content of paragraphs to add classes to them. This is my basic configuration: 'default_attributes' => [
Paragraph::class => [
'class' => static function (Paragraph $node) {
$content = $node->getContent(); // Method does not exist
if (str_starts_with($content, 'danger:')) {
return 'alert alert-danger';
}
return null;
},
],
]Thank you very much! |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
|
Hi there! TL;DR: Use Paragraph nodes do not directly contain text, but some of their descendants do. Here's an example of such an AST (visualized as XML): <document>
<heading level="1">
<text>Hello World!</text>
</heading>
<paragraph>
<text>This is an example of </text>
<strong>
<text>CommonMark</text>
</strong>
<text>.</text>
</paragraph>
</document>To find that text, you'd need to iterate through those nodes, looking for any that implement Or you can use this helper function which does exactly that for you :) |
Beta Was this translation helpful? Give feedback.
Hi there!
TL;DR: Use
$content = StringContainerHelper::getChildText($paragraph);Paragraph nodes do not directly contain text, but some of their descendants do. Here's an example of such an AST (visualized as XML):
To find that text, you'd need to iterate through those nodes, looking for any that implement
StringContainerInterface, and concatenating what those contain.Or you can use this helper function which does exactly that for you :)