eZ Community » Blogs » A Fowler » is_empty for strings

By

A Fowler

is_empty for strings

Friday 04 November 2011 5:11:31 pm

  • Currently 5 out of 5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

A template operator for testing for empty strings would be nice, for testing whether string attributes have any valid value.  I'm thinking of something like empty($val) or is_empty($val).  I can't believe it's not there-- am I missing it somewhere?

UPDATE: You can use PHP's empty() function by enabling it in template.ini.append.php.  In my example, I rename it to is_empty to match the other similar template operators such as is_set:

[PHP]
PHPOperatorList[is_empty]=empty

Before finding about the PHPOperatorList solution above, the closest thing I had found was count_chars($dataMap.attr.content) which returns 0 for an empty string.

I was also using $dataMap.attr.content|trim|ne('') to test for an empty value, to protect against interpreting bogus whitespace as a value.

Related discoveries

I discovered that the cond() operator is as good as, or better than, the ternary operator in some languages ( x ? y : z ).  Obviously, it can be used for more than one clause (see the documentation) but with just one clause, I used this to set a variable to the field, or to a default if empty (the third argument):

{def $var = cond($dataMap.attr.content|trim|ne(''),
                 $dataMap.attr.content|trim,
                 'default value')}

If you don't want a default value, it can still be useful. It will return false() if the condition fails.  This will be useful if you want to skip outputting something further down in the code.

{def $var = cond($dataMap.attr.content|trim|ne(''),
                 $dataMap.attr.content|trim)}
...
{if $var}
    {* Some code that is executed only if the attribute had a value *}
{/if}

I also discovered the hard way that some template operators, namely in this case explode, do not always work if you pass the input in as the first argument.  In other words, explode($var, $delim) does not work, whereas $var|explode($delim) does.  I had thought until now that the two forms were interchangeable.

Proudly Developed with from