[Question] #if built in helper is not working as expected
I am using the #if helper, but it is not working as expected. Below is my equal helper code (exception handling removed for clarity):
_handlebars.RegisterHelper("equal", (writer, context, parameters) =>
{
if (parameters.Length != 2)
{
throw new TemplateServiceException(
"The equal helper requires exactly two parameters.");
}
var firstDecimal = Convert.ToDecimal(parameters[0], CultureInfo.InvariantCulture);
var secondDecimal = Convert.ToDecimal(parameters[1], CultureInfo.InvariantCulture);
writer.WriteSafeString(firstDecimal == secondDecimal);
});
Template:
<ul class="list-buffer">
Result of equal helper: {{equal (record_count VerifiedList) 1}}
{{#if (equal (record_count VerifiedList) 1)}}
is ready to pay.
{{else}}
are ready to pay.
{{/if}}
</ul>
I am printing the result of {{equal (record_count VerifiedList) 1}} and it correctly shows False. However, my {{#if... condition is not rendering the else part in the template output. It prints "is ready to pay." even though VerifiedList has 2 records and record_count returns it correctly.
Could the issue be that the equal helper is writing "False" as a string instead of a boolean?
Output
Yes, #if follows the truthy rules of JavaScript, so a non-empty string is truthy.
But result of my equal helper is False.
No, it’s “False”
You mean writer.WriteSafeString(firstDecimal == secondDecimal); or writer.Write(firstDecimal == secondDecimal); always write it as string? Can we change this behavior ?
I tried writer.Write<Boolean>(firstDecimal == secondDecimal); but it also did not work.
No matter what, it will produce a string.
Any way,the only solution just like below code:
//注册eq等于
handlebars.RegisterHelper("eq", (writer, context, parameters) =>
{
if (parameters.Length == 2 && parameters[0]?.ToString() == parameters[1]?.ToString())
{
writer.Write(true);
}
else
{
writer.Write("");
}
});
writer.Write(""); can be work!
This is by design — WriteSafeString(bool) produces the string "False", and any non-empty string is truthy in Handlebars (matching JavaScript semantics). To use a helper result in {{#if}}, the helper should write an empty string for falsy or use a block helper pattern:
handlebars.RegisterHelper("equal", (writer, context, parameters) =>
{
var a = Convert.ToDecimal(parameters[0], CultureInfo.InvariantCulture);
var b = Convert.ToDecimal(parameters[1], CultureInfo.InvariantCulture);
writer.Write(a == b ? "true" : ""); // empty string is falsy
});
Or use a block helper so the truthiness evaluation happens inside the helper itself rather than through string output. Closing as this is working as intended.