Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 小枝上的Djangos truncatewords_Php_Django_Symfony_Twig - Fatal编程技术网

Php 小枝上的Djangos truncatewords

Php 小枝上的Djangos truncatewords,php,django,symfony,twig,Php,Django,Symfony,Twig,Django有一个名为truncatewords和truncatewords_html的过滤器,它有一个类似的函数/在twig中实现相同功能的最佳方法是什么(后端是symfony) Twigs slice函数不是我想要的,因为它不尊重空格/单词。您可以创建一个使用正则表达式获得所需内容的函数: 类TruncateWordsExtension扩展了AbstractExtension { 公共函数getFilters() { 返回[ 新TwigFilter('truncatewords',[$thi

Django有一个名为
truncatewords
truncatewords_html
的过滤器,它有一个类似的函数/在twig中实现相同功能的最佳方法是什么(后端是symfony)

Twigs slice函数不是我想要的,因为它不尊重空格/单词。

您可以创建一个使用正则表达式获得所需内容的函数:

类TruncateWordsExtension扩展了AbstractExtension
{
公共函数getFilters()
{
返回[
新TwigFilter('truncatewords',[$this,'truncatewords'),
];
}
公共函数truncateWords($text,$maxWords)
{
$regex='/(\w+[\w\s]+){0',.($maxWords-1)。'}(\w+/”;
preg_match($regex,$text,$matches);
返回$matches[0]??“”;
}
}

truncatewords\uHTML
将有点复杂,假设您希望保留html标记结构并只截断其中的单词,但至少您有一个起点。

给出示例输入和预期输出。许多django开发人员可能不熟悉拆分成单词后的
Twigs
切片,然后再次合并可能会起作用,不是吗?例如“这是一个句子”,你想拆分它然后再次合并它们吗?我假设Moritz想生成一个摘要文本,不想剪切单词。