2

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}}

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

you may want to see this post: stackoverflow.com/questions/59269178/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.