[英]Twig - get the number of words from a string
I am using craft cms, that uses twig templating, and would like to get the number of words from the string. 我正在使用工艺cms,它使用twig模板,并希望从字符串中获取单词的数量。 I have tried with using the PHP function
str_word_count()
: 我试过使用PHP函数
str_word_count()
:
{% for entry in entries %}
<a href="{{ entry.url }}">
<div class="media-object">
<div class="small-4 columns">
<div class="media-object-section">
<img src= "{{ entry.topImage.first().getUrl('square') }}">
</div>
</div>
<div class="small-8 columns">
<div class="media-object-section main-section">
<h4>{{ entry.title }}</h4>
{% set numberOfWords = str_word_count(entry.summary) %}
<p>{{ entry.summary |split(" ")|slice(0, 15)|join(" ") }}</p>
<p>{{ entry.dateUpdated | date('j. F Y') }}</p>
</div>
</div>
</div>
</a>
{% endfor %}
But, I got an error: 但是,我收到了一个错误:
Unknown "str_word_count" function.
未知的“str_word_count”函数。
How can I get the number of words from the string in the twig template? 如何从树枝模板中的字符串中获取单词数?
制作自定义扩展并使用其中的任何PHP函数: https : //symfony.com/doc/current/templating/twig_extension.html
Well, as suggested by Tomas, I wrote my own twig (filter) function for this case: 好吧,正如Tomas所建议的,我为这种情况编写了自己的twig(过滤器)函数:
<?php
namespace AppBundle\TwigExtensions;
use Symfony\Bundle\FrameworkBundle\Routing\Router;
use Twig\TwigFilter;
class TwigExtensions extends \Twig_Extension
{
/**
* this is needed
*
* @return string
*/
public function getName()
{
return 'your_twig_extensions';
}
/**
*
* @return array
*/
public function getFunctions()
{
return array();
}
/**
*
*
* @return array
*/
public function getFilters()
{
return array(
new \Twig_SimpleFilter('strWordCount', array($this, 'strWordCount')),
);
}
/**
* count Words in string
*
* @return string
*/
public function strWordCount($text = null)
{
return str_word_count($text);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.