Posts for October 2015

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:
/**
 * Splits the string into an array.
 *
 * <pre>
 *  {{ "one,two,three"|split(',') }}
 *  {# returns [one, two, three] #}
 *
 *  {{ "one,two,three,four,five"|split(',', 3) }}
 *  {# returns [one, two, "three,four,five"] #}
 *
 *  {{ "123"|split('') }}
 *  {# returns [1, 2, 3] #}
 *
 *  {{ "aabbcc"|split('', 2) }}
 *  {# 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;
}