M
M
materlelik2014-09-19 23:00:17
PHP
materlelik, 2014-09-19 23:00:17

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;
}

How to attach this function to Twig {{article.description}} ?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
My joy, 2014-09-26
@t-alexashka

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.

T
Twist, 2014-09-20
@bboytiwst

twig.sensiolabs.org/doc/advanced.html
everything is described here

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question