Iterating through a Map<String,String>

1,910 views
Skip to first unread message

r...@uvasoftware.com

unread,
Dec 30, 2015, 12:11:03 PM12/30/15
to mustache.java
Howdy folks and apologies in advance if this is an obvious question but I have not been able to find a solution that works yet with this mustache implementation.

The gist is, I'm trying to iterate over a Map<String,String> in my template and spew some table rows from it, like this: 


{{#hasMetadata}}
    <table class="table table-striped table-condensed">
        <thead>
        <tr>
            <td>Key</td>
            <td>Value</td>
        </tr>
        </thead>
        <tbody>
        {{#job.userMetadata}}
            <tr>
                <td>{{@key}}</td>
                <td>{{@value}}</td>
            </tr>
        {{/job.userMetadata}}

        </tbody>
    </table>

{{/hasMetadata}}


Pay no attention to the {{@key}} and {{@value}} in there that's just my last attempt at making this work. Needless to say, I can work around this issue but I'm sure there must be an elegant way to handle this that I'm missing. Oh, btw, I did calling .entrySet() in that map without much luck. 

Cheers and thanks in advance, 

- Rafael 

Michael Hixson

unread,
Dec 30, 2015, 6:19:01 PM12/30/15
to mustac...@googlegroups.com
DefaultMustacheFactory factory = new DefaultMustacheFactory();
factory.setObjectHandler(new ReflectionObjectHandler() {
@Override
protected boolean areMethodsAccessible(Map<?, ?> map) {
return true;
}
});

{{#job.userMetadata.entrySet}}
<tr>
<td>{{key}}</td>
<td>{{value}}</td>
</tr>
{{/job.userMetadata.entrySet}}

https://github.com/spullara/mustache.java/blob/28bab527f3e4149b858d8bc726100fe5e41516a4/compiler/src/test/java/com/github/mustachejava/MapNonGetMethodsTest.java#L49

Alternatively, you could change the type of job.userMetadata to an
entry set rather than a map in the backing code. If the type of "job"
is used for other purposes besides backing this Mustache template
though, that might be inconvenient for you. (I try to avoid exposing
types from my business logic into Mustache templates for reasons like
this -- separation of concerns.)

-Michael
> --
> You received this message because you are subscribed to the Google Groups
> "mustache.java" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to mustachejava...@googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.

Rafael Ferreira

unread,
Dec 30, 2015, 6:42:24 PM12/30/15
to mustac...@googlegroups.com
That makes total sense, thanks!
> You received this message because you are subscribed to a topic in the Google Groups "mustache.java" group.
> To unsubscribe from this topic, visit https://groups.google.com/d/topic/mustachejava/UmVGdNtjlpM/unsubscribe.
> To unsubscribe from this group and all its topics, send an email to mustachejava...@googlegroups.com.
Reply all
Reply to author
Forward
0 new messages