samskivert / jmustache

A Java implementation of the Mustache templating language.
Other
834 stars 128 forks source link

Displaying key of Map #82

Closed lsarni closed 8 years ago

lsarni commented 8 years ago

Hello, I´m using swagger-codegen which uses this to handle the mustache templates. I was wondering if there is something I could use to display the key while iterating on a map. Something like the first anwser from here maybe? Thanks!

samskivert commented 8 years ago

You could almost do it with the built-in stuff, because you could call entrySet on the map and then call getKey and getValue on those. Like so:

{{#map.entrySet}}
{{key}} = {{value}}
{{/map.entrySet}}

However, JMustache has special handling for Map because it assumes you want to look up the key in the map not look up methods on the actual Map class (like you might for your own custom data types). So it looks for a map entry named entrySet which obviously doesn't exist.

You can work around this in the meanwhile by customizing the Mustache.Compiler (assuming swagger-codegen lets you do that):

Mustache.Compiler comp = Mustache.compiler().withCollector(new DefaultCollector() {
    @Override public Mustache.VariableFetcher createFetcher (Object ctx, String name) {
        if (ctx instanceof Map<?,?> && name == "entrySet") {
            return new Mustache.VariableFetcher() {
                public Object get (Object ctx, String name) throws Exception {
                    return ((Map<?,?>)ctx).entrySet();
                }
            };
        } else {
            return super.createFetcher(ctx, name);
        }
    }
});

This allows you to use the above code as is by specializing the lookup of entrySet on any object that is of type Map.

I'll make this {{#map.entrySet}} construction work out of the box, but it won't be available until I do the next release and then swagger-codegen updates to use it, so the workaround is probably useful in the meanwhile.

lsarni commented 8 years ago

So, if I made a list of objects, mods:

public class Mod 
{
    public int nro;
}

Could I access the variable like this:

{{#mods}}
Nro = {{mods.nro}}
{{/mods}}

Thanks!

samskivert commented 8 years ago

You don't need to repeat mods inside:

{{#mods}}
Nro = {{nro}}
{{/mods}}

Also, this is a forum for reporting issues with JMustache, not asking questions about how to use it. Please just read documentation and try things yourself rather than filing issues every time you have a question about how to use Mustache. There are dozens of implementations of Mustache and thousands of people posting about it on the web. A simple Google search or five minutes of trying something with code would have answered this question.

lsarni commented 8 years ago

Thanks, and sorry.