handlebars.java icon indicating copy to clipboard operation
handlebars.java copied to clipboard

Handlebars.Utils.isEmpty not implemented for Maps

Open dontgitit opened this issue 5 years ago • 2 comments

Hi,

Not sure if it's intentional, but Utils.isEmpty doesn't have a case for Maps; 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!

dontgitit avatar Mar 08 '19 02:03 dontgitit

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

dontgitit avatar Mar 08 '19 02:03 dontgitit

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.

Kobee1203 avatar Mar 03 '22 09:03 Kobee1203