how to display property/key name in HandleBars.net

1.6k Views Asked by At

Hi this code works perfectly fine for Handlebar.js. What should I do to display key/property through c#/HandleBars.net ?

 {{#each myObject}}
    {{#if this.length}}
    <b>{{@key}}</b>
    {{#each this}}
    <li>{{this}}</li>
    {{/each}}
    <br>
    {{/if}}
    {{/each}}
2

There are 2 best solutions below

0
On
var htmlTemplateStr = //Open a resource or file containing your HTML template,
                      // and load it into this string

var LoadedTemplate = Handlebars.Compile(htmlTemplateStr);

var contextJson = //create a JSON object that will hold all the variables your 
                  // template will be looking for

var outputHtml = LoadedTemplate(contextJson);

EDIT

Your Key array will be a JSON array member of your JSON object. To display it, you'll need to add a HandleBars each block into your html template. It'll look something like this:

{{#each Key}}
    <!-- HTML to display whatever is in each object in the Key array -->
{{/each}}
0
On

Update 5/14/16

Version 1.6.6 of Handlebars.Net includes 2 changes:

  • Member resolution is case-insensitive (many devs were surprised that {{length}} and {{Length}} could not resolve to the same thing)
    • (In cases where there is an ambiguous match - i.e. Length and length are both present on the object, the binder will prefer the exact match)
  • this can now be used in member paths, e.g. this.length

Original answer

We have had a few issues bubble up in the past few days that involve case sensitivity and member resolution. You are right this template should work as you have it; we're working on fixing that.

In the meantime, if you change {{#if this.length}} to {{#if Length}} it will work as you expect.