pebble icon indicating copy to clipboard operation
pebble copied to clipboard

Extensions for iterables?

Open vgrigoriu opened this issue 4 years ago • 2 comments

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?

vgrigoriu avatar Aug 13 '20 12:08 vgrigoriu

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);

jsatya1963 avatar Feb 11 '21 02:02 jsatya1963

I guess I could give that a try, thanks for the idea!

vgrigoriu avatar Feb 11 '21 04:02 vgrigoriu