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

ClassCastException when comparing variable to static integer value

Open abhimanyuchugh opened this issue 2 years ago • 0 comments

Hi,

I get a ClassCastException when doing a greater than comparison against a static Integer value. It seems to be trying to cast the static int value to String, which triggers the cast exception.

I'm using the latest handlebars.java 4.3.1.

Here's an example template and data json:

{{#if (gt index 0)}}
    <p>Greater than zero</p>
{{else}}
    <p>Less than or equal to zero</p>
{{/if}}
{
  "index": 0
}

Exception stack trace:

com.github.jknack.handlebars.HandlebarsException: template.html:1:3: java.lang.ClassCastException: class java.lang.Integer cannot be cast to class java.lang.String (java.lang.Integer and java.lang.String are in module java.base of loader 'bootstrap')
    template.html:1:3
	at [email protected]/java.lang.String.compareTo(String.java:140)
	at app//com.github.jknack.handlebars.helper.ConditionalHelpers.cmp(ConditionalHelpers.java:401)
	at app//com.github.jknack.handlebars.helper.ConditionalHelpers$3.apply(ConditionalHelpers.java:132)
	at app//com.github.jknack.handlebars.internal.Variable.value(Variable.java:167)
	at app//com.github.jknack.handlebars.internal.VarParam.apply(VarParam.java:46)
	at app//com.github.jknack.handlebars.internal.HelperResolver.determineContext(HelperResolver.java:146)
	at app//com.github.jknack.handlebars.internal.Block.merge(Block.java:204)
	at app//com.github.jknack.handlebars.internal.BaseTemplate.apply(BaseTemplate.java:126)
	at app//com.github.jknack.handlebars.internal.TemplateList.merge(TemplateList.java:95)
	at app//com.github.jknack.handlebars.internal.BaseTemplate.apply(BaseTemplate.java:126)
	at app//com.github.jknack.handlebars.internal.BaseTemplate.apply(BaseTemplate.java:114)
	at app//com.github.jknack.handlebars.internal.ForwardingTemplate.apply(ForwardingTemplate.java:72)

Workaround Putting the static value in quotes seems to solve the issue, i.e.

{{#if (gt index "0")}}
    <p>Greater than zero</p>
{{else}}
    <p>Less than or equal to zero</p>
{{/if}}

But it would be great if the library is able to figure out that both the variable and static value are numbers and casting the static value to String is not needed.

Thanks!

abhimanyuchugh avatar Jan 13 '23 16:01 abhimanyuchugh