0

Java code --

List<String> table = Lists.newArrayList();
........

Template Code --

 {{#each table}}
    <td height="28" width="27"><h1> {{table.length}}</h1></td>
    <td height="28" width="27"><h1> {{table.size}}</h1></td>
    <td height="28" width="27"><h1> {{table.count}}</h1></td>
    <td height="28" width="27"><h1> {{../../table.length}}</h1></td>
    <td height="28" width="27"><h1> {{../table.length}}</h1></td>
 {{/each}}

I am trying to get the length of the list in the handlebar template. But all those lines above I tried don't work! I am wondering where I do wrongly. What's the right way to get the length of iterator in handlebar java?

Thanks in advance!

Haoyu Chen
  • 1,760
  • 1
  • 22
  • 32
  • 1
    Instead of using handlebar, I decided to set length variable in java side, and directly apply it to the code. Java is much easier and straightforward for this one. – Haoyu Chen Mar 01 '17 at 23:05

2 Answers2

2

I think the problem is that the size method on List isn't getSize() -- it's just size(). And the default Handlebars Java "[uses] the JavaBean methods (i.e. public getXxx and isXxx methods) and Map as value resolvers", so methods like size() won't work.

Basically you want to build a context that includes MethodValueResolver, which handles any public method.

From here:

Context context = Context
    .newBuilder(model)
    .resolver(MethodValueResolver.INSTANCE)
    .build();

Also, multiple value resolvers example.


Or, since MethodValueResolver is kinda overkill, maybe it's actually best to just pass the length down explicitly, as you mention in your comment.

Max
  • 4,882
  • 2
  • 29
  • 43
1

Here's a javascript/html solution. You essentially have to grab the length outside of the {{#each}}...{{/each}}.

<!DOCTYPE html>
<html>
<head>
    <title>Page Title</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/2.0.0/handlebars.js"></script>
</head>
<body>

<script id="t" type="text/x-handlebars">
    <p>My table length is {{table.length}}</p>
    {{#each table}}
    <p>Stay for some {{a}} and {{b}}</p>
    {{/each}}
</script>

<script>
    Handlebars.registerHelper('testHelper', function(ignore, opt) {
        var results = '';
        data.forEach(function (item) {
            results += opt.fn(item);
        });
        return results;
    });

    var table = [
        { a: 'tea', b: 'cookie' },
        { a: 'coffee', b: 'cake' }
    ];
    var t = Handlebars.compile($('#t').html());
    $('body').append(t({ table: table }));
</script>
</body>
</html>
rasmeister
  • 1,986
  • 1
  • 13
  • 19