Reputation: 7429
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);
}
}
Upvotes: 4
Views: 3875
Reputation: 15930
There's a simpler solution:
backend:
Handlebars handlebars = new Handlebars();
handlebars.registerHelper("eq", ConditionalHelpers.eq);
frontend:
{{#eq "a" "a"}}HURRA!{{/eq}}
Source: official documentation
Upvotes: 4
Reputation: 2208
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}}
Upvotes: 6