Last active
October 14, 2022 14:13
-
-
Save iris-i/8a3f91055cbb33149abbb57f15d33d21 to your computer and use it in GitHub Desktop.
Custom Twig Filter for Drupal 8: Gets the first paragraph of a view field as opposed to truncating text at a particular character count
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Drupal\dd_base\TwigExtension; | |
class DdBaseFirstParagraphFilter extends \Twig_Extension { | |
/** | |
* Generates a list of all Twig filters that this extension defines. | |
*/ | |
public function getFilters() { | |
return [ | |
new \Twig_SimpleFilter('getparagraph', array($this, 'getFirstParagraph')), | |
]; | |
} | |
/** | |
* Gets a unique identifier for this Twig extension. | |
*/ | |
public function getParagraph() { | |
return 'dd_base.twig_extension'; | |
} | |
/** | |
* Cut the full string at the first linebreak. If it returns empty, display the first 150 chars | |
* | |
* @param string $fulltext | |
* Text body | |
* | |
* @return string | |
* First paragraph of text, or 2 paragraphs if 1st is < 100 chars. | |
*/ | |
function getFirstParagraph($fulltext) { | |
$fulltext = trim($fulltext); | |
$first_paragraph = substr($fulltext, 0, strpos($fulltext, "\n")); | |
$after_first_paragraph = substr($fulltext, strpos($fulltext, "\n") + 1); | |
$second_paragraph = substr($after_first_paragraph, 0, strpos($after_first_paragraph, "\n")); | |
$substring_default = substr($fulltext, 0, 150); | |
if ($first_paragraph === '') { | |
$output = $substring_default; | |
} | |
elseif (strlen($first_paragraph) < 200) { | |
$output = $first_paragraph . "\n" . $second_paragraph; | |
} | |
else { | |
$output = $first_paragraph; | |
} | |
return $output; | |
} | |
} |
Hi, Iris-i. I am not very familiar with Drupal functions. How can I use this in my project?
I found a guide here https://medium.com/@thihathit/extending-custom-twig-extension-to-drupal-8-twig-extension-class-d4b99c2177ae But still a haven't been able to make it work.
I see your public function getParagraph() so twig variable should look something like {{ node.field_text.value|getParagraph }}
Is that correct?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Credits to @kducharm