Django有一个名为truncatewords
和truncatewords_html
的过滤器,Truncates a string after a certain number of words.是否有类似的功能/什么是在树枝中实现相同功能的最佳方式(后端的symfony)。
Twigs切片功能不是我正在寻找的,因为它不尊重空格/单词。
你可以创建一个custom Twig Filter,它将使用正则表达式来获得你想要的东西:
class TruncateWordsExtension extends AbstractExtension
{
public function getFilters()
{
return [
new TwigFilter('truncatewords', [$this, 'truncateWords']),
];
}
public function truncateWords($text, $maxWords)
{
$regex = '/((\w+)[\W\s]+){0,' . ($maxWords - 1) . '}(\w+)/';
preg_match($regex, $text, $matches);
return $matches[0] ?? '';
}
}
假设你想要保留HTML标签结构并截断其中的单词,truncatewords_html
会更复杂一些,但至少你有一个起点。