RamblingRoss
The blog of Ross Fruen, a .NET consultant

Add Twig Split filter to Stacey

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:

// 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'),
/**
* Splits the string into an array.
*
* <pre>
* ["one,two,three"]
* {# returns [one, two, three] #}
*
* ["one,two,three,four,five"]
* {# returns [one, two, "three,four,five"] #}
*
* ["123"]
* {# returns [1, 2, 3] #}
*
* ["aabbcc"]
* {# returns [aa, bb, cc] #}
* </pre>
*
* @param string $value A string
* @param string $delimiter The delimiter
* @param int $limit The limit
*
* @return array The split string as an array
*/

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).

Thanks!

Thank you for submitting your comment, it will appear here after moderation is complete.

Sorry

There was a problem sending your comment, please try again.