Djangos在树枝上截断词

问题描述 投票:-1回答:1

Django有一个名为truncatewordstruncatewords_html的过滤器,Truncates a string after a certain number of words.是否有类似的功能/什么是在树枝中实现相同功能的最佳方式(后端的symfony)。

Twigs切片功能不是我正在寻找的,因为它不尊重空格/单词。

php django symfony twig
1个回答
1
投票

你可以创建一个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会更复杂一些,但至少你有一个起点。

© www.soinside.com 2019 - 2024. All rights reserved.