[英]Twig - get the number of words from a string
我正在使用工藝cms,它使用twig模板,並希望從字符串中獲取單詞的數量。 我試過使用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 %}
但是,我收到了一個錯誤:
未知的“str_word_count”函數。
如何從樹枝模板中的字符串中獲取單詞數?
制作自定義擴展並使用其中的任何PHP函數: https : //symfony.com/doc/current/templating/twig_extension.html
好吧,正如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.