Repository navigation
How to get Node contents #995
Answered
by
colinodell
natanfelles
asked this question in
Q&A
|
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! |
Answered by
colinodell
Sep 12, 2023
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 :) |
1 reply
Answer selected by
natanfelles
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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 :)