Reputation: 81
I am trying to use a Handlebars.Net template to iterate over a list of string and to render either one thing or the other based on the value of the string.
This is a cut-down example of what I am trying to achieve. I have an object with a list of string property, and a template that loops through the list and renders some HTML based on the value of the string:
Simple object with list:
public class Box
{
public List<string> BoxItems { get; set; }
}
Simple template to iterate over the list and render one thing or the other:
{{#each Box.BoxItems }}
{{#if this == "item" }}
<p>This is a box item</p>
{{else}}
<p>This is not a box item</p>
{{/if}}
{{/each}}
I have tried registering my own helper but haven't managed to make this work.
How can I can get this to work using the Handlebars.Net port (not the HandlebarsJS version)?
EDIT:
The helper I tried using that doesn't work is this:
handlebars.RegisterHelper("eq_test", (a, b) => a.ToString().Equals(b.ToString()));
and it is used in the template like this:
{{#each Box.BoxItems }}
{{#if (eq_test this "item") }}
<p>This is a box item</p>
{{else}}
<p>This is not a box item</p>
{{/if}}
{{/each}}
Upvotes: 2
Views: 1181
Reputation: 81
Answering my own question,
I registered the helper like this:
handlebars.RegisterHelper("isEq", (ctx, args) => {
if (args.Length != 2)
{
throw new ArgumentOutOfRangeException();
}
string str1 = args[0].ToString();
string str2 = args[1].ToString();
return str1 == str2;
});
And then I used it in the template like this:
{{#each Box.BoxItems }}
{{#if (isEq this item) }}
<p>This is a box item</p>
{{else}}
<p>This is not a box item</p>
{{/if}}
{{/each}}
Obviously this is not a perfect example of how to do this. There is no real checking done on the parameters and it is clearly a string comparison.
But hopefully it will save somebody a few hours of figuring out how to register a simple equality check helper for Handlebars.Net.
Upvotes: 4