1

我一直在尝试使用语法遍历项目的数组列表,{% 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 实现,结果总是这样。在进行可迭代测试时,数组列表返回 true,所以我认为它应该可以使用 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);
4

1 回答 1

1

这取决于单例映射的使用。改用一个HashMap,应该可以工作。

解释。Scope初始化如下:

public Scope(Map<String, Object> backingMap, boolean isLocal) {
    this.backingMap = (Map)(backingMap == null?new HashMap():backingMap);
    this.isLocal = isLocal;
}

所以它实际上重用了您提供的地图。当它调用putMap,它会抛出一个异常,因为它是一个单例。

于 2016-11-11T09:20:33.360 回答