RamblingRoss
The blog of Ross Fruen, a .NET consultant

Add Twig Split filter to the Stacey CMS

The Stacey 3.0.0 CMS ships with quite an old version of Twig that is missing many useful functions.

Whilst developing the blog template used by this site it was necessary to bring in the split filter to Stacey's copy of Twig.

To achieve this the following sites are required:

  • Open the /app/parsers/Twig/Extension/Core.php file
  • Locate the getFilters() function and extend the array helpers to include the 'split' formatter, i.e.
// array helpers
'join' => new Twig_Filter_Function('twig_join_filter'),
'reverse' => new Twig_Filter_Function('twig_reverse_filter'),
'split' => new Twig_Filter_Function('twig_split_filter', array('needs_environment' => true)),
'length' => new Twig_Filter_Function('twig_length_filter', array('needs_environment' => true)),
'sort' => new Twig_Filter_Function('twig_sort_filter'),
'merge' => new Twig_Filter_Function('twig_array_merge'),
  • Add the following function to the end of the file:
function twig_split_filter(Twig_Environment $env, $value, $delimiter, $limit = null)
{
if (!empty($delimiter)) {
return null === $limit ? explode($delimiter, $value) : explode($delimiter, $value, $limit);
}

if (!function_exists('mb_get_info') || null === $charset = $env->getCharset()) {
return str_split($value, null === $limit ? 1 : $limit);
}

if ($limit <= 1) {
return preg_split('/(?<!^)(?!$)/u', $value);
}

$length = mb_strlen($value, $charset);
if ($length < $limit) {
return array($value);
}

$r = array();
for ($i = 0; $i < $length; $i += $limit) {
$r[] = mb_substr($value, $i, $limit, $charset);
}

return $r;
}

Add a comment

If you want your comment to appear on this page please complete the form below. Your name and email address are optional, although the latter will be required if you want a response. Your email address will not appear against your comment and will only be used to correspond with yourself (where appropriate).