pebble
pebble copied to clipboard
Extensions for iterables?
I was wondering if it would make sense to have "iterable resolvers", similar to attribute resolvers. One use case is using JsonNode
, the type that Jackson uses to represent json. There are two types, ObjectNode
and ArrayNode
that represent objects (maps) and arrays respectively, but they don't implement Iterable
directly. It's not difficult to get from them to iterables, but you'd need a hook exposed by Pebble probably in ForNode. It would probably make sense to also use these iterable resolvers in EmptyTest.
This would allow to write something like the following:
Map<String, Object> context = new HashMap<>();
context.put("a", new ObjectMapper().readTree("{\"b\":[],\"c\":[1,2,3]}"));
and render a template like:
{% for kv in a %}
{% if kv.value is empty %}
<{{kv.key}}:{% for n in kv.value %}{{ n }}{% endfor %}>
{% endif %}
{% endfor %}
to get:
<c:123>
What do you think?
Why not load the raw JSON as a Map
?
Map<String, Object> map = mapper.readValue("{\"b\":[],\"c\":[1,2,3]}", new TypeReference<Map<String, Object>>() {});
context.put("a", map);
I guess I could give that a try, thanks for the idea!