handlebars.java
handlebars.java copied to clipboard
Handlebars.Utils.isEmpty not implemented for Maps
Hi,
Not sure if it's intentional, but Utils.isEmpty
doesn't have a case for Map
s; they don't inherit Collection
nor Iterable
, so even the empty map {}
isn't considered "empty". That seems strange given []
is considered "empty".
Is this intentional, or an oversight?
Thanks!
(P.S. I'm referring to this method: https://github.com/jknack/handlebars.java/blob/master/handlebars/src/main/java/com/github/jknack/handlebars/Handlebars.java#L188)
I had the same problem. I overrided IfHelper, UnlessHelper and WithHelper and I used my own HelperUtils class.
public final class HelperUtils {
private HelperUtils() {
}
public static boolean isFalsy(final Options options, final Object value) {
if (value instanceof Map) {
return ((Map<?, ?>) value).isEmpty();
}
return options.isFalsy(value);
}
}
Example with my IfHelper class:
public class IfHelper implements Helper<Object> {
/**
* A singleton instance of this helper.
*/
public static final Helper<Object> INSTANCE = new IfHelper();
/**
* The helper's name.
*/
public static final String NAME = com.github.jknack.handlebars.helper.IfHelper.NAME;
@Override
public Object apply(final Object context, final Options options) throws IOException {
Options.Buffer buffer = options.buffer();
if (HelperUtils.isFalsy(options, context)) {
buffer.append(options.inverse());
} else {
buffer.append(options.fn());
}
return buffer;
}
}
It's not great to have to do this, but I haven't found any other solutions. Ideally, the library should integrate the case for the map.