Context
In handlebars, I want to compare two values and print X or Y depending if they are equal or not. I successfully registered a comparison helper:
private static string GetArgumentValue(object argument)
{
if (argument.GetType().Name == "UndefinedBindingResult")
{
return (string) argument.GetType().GetField("Value").GetValue(argument);
}
return argument.ToString();
}
public void RegisterHelper()
{
Handlebars.RegisterHelper("ifCond", (output, context, arguments) =>
{
var value1 = GetArgumentValue(arguments[0]);
var operation = GetArgumentValue(arguments[1]);
var value2 = GetArgumentValue(arguments[2]);
var returnValue1 = GetArgumentValue(arguments[3]);
var returnValue2 = GetArgumentValue(arguments[4]);
switch (operation)
{
case "eq":
output.Write(value1 == value2 ? returnValue1 : returnValue2);
break;
case "ne":
output.Write(value1 != value2 ? returnValue1 : returnValue2);
break;
default:
throw new Exception("ifCond: Unrecognized operation");
}
});
}
And I am using it like this:
'{{ifCond MyData eq 01 X Y}}'
Whats the problem?
MyData is a variable with value 01 This means that comparing MyData to 01 should print X, unfortunately, it prints Y (meaning they are not equal). This is because all of the arguments are of type UndefinedBindingResult except the 3rd one that is integer. That is why comparing MyData (01) to 1 is not equal.
Question: Whats the right way to pass a string to my helper function? Obviously, it interprets the 3rd argument - 01, as an integer and provides it as just 1.
Disclaimer: I realize my explanation is not very good, but my Handlebards knowledge is limited.
To handle a value as a string, just use
"
, like:See working example: https://dotnetfiddle.net/7JLLPe
And if you need more helpers, you can also checkout this project (which also includes the
String.Equal
helper method):https://github.com/Handlebars-Net/Handlebars.Net.Helpers