Custom teasers in Drupal 6 with views 2

Refine the text lenght of your views teaser texts

Update: With the new releases of Views it is possible to do all the trimming and html stripping directly from the views UI.

While I was developing this website I run into the need of having total control over the teasers of my contents especially while using views to extract them.  Probably if you have just one content type you can manage it with the default option in drupal administration.

The simplest solution I have found is to use the neat_trim function. So what you have to do is just copy and paste the following function into your theme template.php file (just remember not to copy the "?>" php closure):

 

<?php

function neat_trim($str, $n, $delim='&hellip;') {

$len = strlen($str);

if ($len > $n) {

preg_match('/(.{' . $n . '}.*?)\b/', $str, $matches);

return rtrim($matches[1]) . $delim;

}

else {

return $str;

}

}

?>

 

Now you just need to go on each template file where you want this function (you can easily find and create them inspecting your views from the views admin panel) and put the following code:

 

<?php

$string = neat_trim($output, 100);

print $string;

?>

 

This will print out the content limited to 100 characters or the full content in case it has less then 100 characters. A small extra tip if you are using a WYIWYG editor or if you have some HTML code in your page when you create your content is to add a strip_tags so as to remove any html tag in you text to avoid unwanted results on your page. So the code will look like that:

 

<?php

$output = strip_tags($output);

$string = neat_trim($output,100);

print $string;

?>

 

This is how the news on the home page and the blog block teaser were created in this website.

19 Jan 2009