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

How about adding a helper for contains?

Open spacether opened this issue 2 years ago • 1 comments

How about adding a helper for contains? It would work for maps and sets and check for key presence.

{{#contains someMap "someKey"}}
{{/contains}}

{{#contains someSet "someKey"}}
{{/contains}}

spacether avatar Feb 04 '23 06:02 spacether

This works:

public enum ContainsHelper implements Helper<Object> {

    /**
     * Indicates the set or map contains the given key
     * For example:
     *
     * <pre>
     * {{#contains someMap "someKey"}}
     * {{/contains}}
     * </pre>
     *
     * <pre>
     * {{#contains someSet "someItem"}}
     * {{/contains}}
     * </pre>
     */
    contains {
        @Override public Object apply(final Object a, final Options options) throws IOException {
            Object b = options.param(0, null);
            boolean result;
            if (Map.class.isInstance(a)) {
                Map mapA = (Map) a;
                result = mapA.containsKey(b);
            } else if (Set.class.isInstance(a)) {
                Set setA = (Set) a;
                result = setA.contains(b);
            } else {
                result = false;
            }
            if (options.tagType == TagType.SECTION) {
                return result ? options.fn() : options.inverse();
            }
            return result
                    ? options.hash("yes", true)
                    : options.hash("no", false);
        }
    }
}

And I created it in https://github.com/openapi-json-schema-tools/openapi-json-schema-generator/pull/130

spacether avatar Feb 04 '23 06:02 spacether