Handlebars-Net/Handlebars.Net

[Question] #if built in helper is not working as expected

Opened this issue · 7 comments

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

image

rexm commented

Yes, #if follows the truthy rules of JavaScript, so a non-empty string is truthy.

But result of my equal helper is False.

rexm commented

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.

rexm commented

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!