schmittjoh/twig.js — pull request #53 by h2s (2013-03-18 20:32:01+00:00)
Title: The length filter should not throw an error if the parameter is not countable

The `length` filter currently throws an error if the parameter given can't be counted. In order to be compatible with templates originally written for PHP Twig, this shouldn't happen.

PHP Twig does the following in its length filter:

return is_scalar($thing) ? strlen($thing) : count($thing);

That code works with all scalar values, including integers and `null`. The `length` filter in twig.js simply calls `twig.count`, which does the following:

if (goog.isArray(v)) {
return v.length;
}
if (goog.isString(v)) {
return v.length;
}
if (goog.isObject(v)) {
return goog.object.getCount(v);
}
throw Error((typeof v) + " is not countable.");

This is a pain if you have a large number of existing Twig templates that work fine with PHP Twig but trip up on this with twig.js. I propose amending `twig.filter.length` to something like the following:

twig.filter.length = function(env, value) {
if (twig.countable(value)) {
return twig.count(value);
} else if (value) {
return 1;
} else {
return 0;
}
};

I'm more than happy to put together a proper pull request for this if you agree in principle. What do you think?