Answer the question
In order to leave comments, you need to log in
How to display a certain number of words in Twig?
Friends, there is a function to show a certain number of words
function first_n_words($text, $number_of_words) {
// Where excerpts are concerned, HTML tends to behave
// like the proverbial ogre in the china shop, so best to strip that
$text = strip_tags($text);
// \w[\w'-]* allows for any word character (a-zA-Z0-9_) and also contractions
// and hyphenated words like 'range-finder' or "it's"
// the /s flags means that . matches \n, so this can match multiple lines
$text = preg_replace("/^\W*((\w[\W'-]*\b\W*){1,$number_of_words}).*/ms", '\\1', $text);
// strip out newline characters from our excerpt
return str_replace("\n", "", $text);
}
// excerpt plus link if shortened
function truncate_to_n_words($text, $number_of_words, $url, $readmore = 'Read More') {
$text = strip_tags($text);
$excerpt = first_n_words($text, $number_of_words);
// we can't just look at the length or try == because we strip carriage returns
if( str_word_count($text) !== str_word_count($excerpt) ) {
$excerpt .= '... <br><a href="'.$url.'">'.$readmore.'</a>';
}
return $excerpt;
}
Answer the question
In order to leave comments, you need to log in
And I would not advise to fasten some functions, it seems to me much easier to use this construction:
in the 0:5 array, specify how many words to output, and that's it.
Happy development.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question