在 Pebble 模板引擎中不能使用 for 标签遍历数组列表
Cannot use for tag to iterate through Array List in Pebble Template Engine
我一直在尝试使用 {% for item in items %}
语法遍历项目的数组列表,但无济于事。
继续投掷
java.lang.UnsupportedOperationException
at java.util.AbstractMap.put(AbstractMap.java:209)
at com.mitchellbosecke.pebble.template.Scope.put(Scope.java:53)
at com.mitchellbosecke.pebble.template.ScopeChain.put(ScopeChain.java:61)
at com.mitchellbosecke.pebble.template.EvaluationContext.put(EvaluationContext.java:162) exception.
尝试了原始数组、映射、许多类型的 List 实现,结果总是这样。在进行可迭代测试时,数组列表 returns 为真,所以我认为它应该可以使用 for 标记进行迭代。难道我做错了什么?请在下面找到代码。
PebbleTemplate template = pebbleEngine.getTemplate(
"{% if menuItems is iterable %}{% for menuItem in menuItems %}" +
" \"{{ menuItem }}\" this" +
"{% endfor %}{% else %}nope{% endif %}");
StringWriter writer = new StringWriter();
List<String> menuItems = new ArrayList<>();
menuItems.add("menu item1");
menuItems.add("menu item2");
menuItems.add("menu item 3");
template.evaluate(writer, Collections.<String,Object>singletonMap("menuItems", menuItems));
System.out.println(writer);
这取决于单例映射的使用。
改用 HashMap
应该可以。
说明。 Scope
初始化如下:
public Scope(Map<String, Object> backingMap, boolean isLocal) {
this.backingMap = (Map)(backingMap == null?new HashMap():backingMap);
this.isLocal = isLocal;
}
所以它实际上重复使用了您提供的地图。当它在 Map
上调用 put
时,它会抛出异常,因为它是一个单例。
我一直在尝试使用 {% for item in items %}
语法遍历项目的数组列表,但无济于事。
继续投掷
java.lang.UnsupportedOperationException
at java.util.AbstractMap.put(AbstractMap.java:209)
at com.mitchellbosecke.pebble.template.Scope.put(Scope.java:53)
at com.mitchellbosecke.pebble.template.ScopeChain.put(ScopeChain.java:61)
at com.mitchellbosecke.pebble.template.EvaluationContext.put(EvaluationContext.java:162) exception.
尝试了原始数组、映射、许多类型的 List 实现,结果总是这样。在进行可迭代测试时,数组列表 returns 为真,所以我认为它应该可以使用 for 标记进行迭代。难道我做错了什么?请在下面找到代码。
PebbleTemplate template = pebbleEngine.getTemplate(
"{% if menuItems is iterable %}{% for menuItem in menuItems %}" +
" \"{{ menuItem }}\" this" +
"{% endfor %}{% else %}nope{% endif %}");
StringWriter writer = new StringWriter();
List<String> menuItems = new ArrayList<>();
menuItems.add("menu item1");
menuItems.add("menu item2");
menuItems.add("menu item 3");
template.evaluate(writer, Collections.<String,Object>singletonMap("menuItems", menuItems));
System.out.println(writer);
这取决于单例映射的使用。
改用 HashMap
应该可以。
说明。 Scope
初始化如下:
public Scope(Map<String, Object> backingMap, boolean isLocal) {
this.backingMap = (Map)(backingMap == null?new HashMap():backingMap);
this.isLocal = isLocal;
}
所以它实际上重复使用了您提供的地图。当它在 Map
上调用 put
时,它会抛出异常,因为它是一个单例。