Hi there... if i understand u right, u want to get some news and when u show them- to show truncated text.
- So, u know how to get an article/news
- U must print part of the content... in volt.
I will show u some way to do that:
First: You need to make a plugin (helper) (not nessesery to follow my class names): to do that- u need to create a folder helpers (for example). Inside create file with name Volt.php that contain:
<?php
namespace Helpers;
class Volt
{
static function truncateFilter($string, $length = 80, $etc = '...', $break_words = false, $middle = false)
{
$charset = 'UTF-8';
$utf8_modifier = 'u';
if ($charset != 'UTF-8') {
$utf8_modifier = '';
}
if ($length == 0) return '';
// Remove tags
$string = strip_tags($string);
// Go for it
if (extension_loaded('mbstring')) {
if (mb_strlen($string, $charset) > $length) {
$length -= min($length, mb_strlen($etc, $charset));
if (!$break_words && !$middle) {
$string = preg_replace('/\s+?(\S+)?$/' . $utf8_modifier, '', mb_substr($string, 0, $length + 1, $charset));
}
if (!$middle) {
return mb_substr($string, 0, $length, $charset) . $etc;
}
return mb_substr($string, 0, $length / 2, $charset) . $etc . mb_substr($string, - $length / 2, $length, $charset);
}
return $string;
}
// No MBString fallback
if (isset($string[$length])) {
$length -= min($length, strlen($etc));
if (!$break_words && !$middle) {
$string = preg_replace('/\s+?(\S+)?$/', '', substr($string, 0, $length + 1));
}
if (!$middle) {
return substr($string, 0, $length) . $etc;
}
return substr($string, 0, $length / 2) . $etc . substr($string, - $length / 2);
}
return $string;
}
}
Next: You need to include this plugin/helper to your project in loader- just for example: /See Helpers/
$loader->registerNamespaces([
'Controllers' => __DIR__ . '/controllers/',
'Helpers' => __DIR__ . '/helpers/'
]);
Next: Give VOLT our extension: (example): /see Custom filter/
/**
* Setting up the view component
*/
$di->set('view', function () use ($config) {
$view = new View();
$view->setViewsDir($config->application->viewsDir);
$view->registerEngines([
'.volt' => function ($view, $di) use ($config) {
$volt = new VoltEngine($view, $di);
$volt->setOptions([
'compileAlways' => $config->development, // This is mine development var xD
'compiledPath' => $config->application->appCacheDir."volt/",
'compiledSeparator' => '_'
]);
// Custom filters
$volt->getCompiler()->addFilter('truncate', "\Helpers\Volt::truncateFilter");
return $volt;
}
]);
return $view;
}, true);
So: we are almost ready :) If u make all parts work, u can use that helper in volt template like:
<p>{{ primary.content|truncate(90) }}</p>
...and u will got something like "text text text text text..." :)
I hope understand u well.
Good luck :)