4

I am using Handlebars with Dropwizard in Java. I'd like to compare 2 strings and if the are identically, I'd like to do something. I know there are some Helpers within Javascript, but I don't get how to adapt them to java.

I've this code, but question is, how can I add the second value to check whether they are equal.

public enum StringHelper implements Helper<Object> {
     eq {
         @Override
         public Boolean safeApply(final Object value, final Options options) {
           return ((String)value).equals(/*SECOND VALUE*/);
         }
       };

       @Override
       public Boolean apply(Object context, Options options) throws IOException {
         return safeApply(context, options);
       }

       protected abstract Boolean safeApply(final Object value,
                                        final Options options);
     }
}

2 Answers 2

6

First create a class for your custom helpers:

public class HandlebarsHelpers {
    public CharSequence equals(final Object obj1, final Options options) throws IOException {
        Object obj2 = options.param(0);
        return Objects.equals(obj1, obj2) ? options.fn() : options.inverse();
    }
}

Then register that class:

Handlebars handlebars = new Handlebars();
handlebars.registerHelpers(new HandlebarsHelpers());

Use the helper:

{{#equals 'A' type}}
    <p>The type is A</p>
{{else}}
    <p>The type is NOT A</p>
{{/equals}}
0
4

There's a simpler solution:

backend:

Handlebars handlebars = new Handlebars();
handlebars.registerHelper("eq", ConditionalHelpers.eq);

frontend:

{{#eq "a" "a"}}HURRA!{{/eq}}

Source: official documentation

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.