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);
     }
}
Christian
  • 6,961
  • 10
  • 54
  • 82

2 Answers2

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}}
Marco Sulla
  • 15,299
  • 14
  • 65
  • 100
AndreLDM
  • 2,117
  • 1
  • 18
  • 27
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

Marco Sulla
  • 15,299
  • 14
  • 65
  • 100