【问题标题】:Iterating two list in parallel with thymeleaf与 thymeleaf 并行迭代两个列表
【发布时间】:2015-09-11 00:09:11
【问题描述】:

在我当前的 spring-boot 项目中,我有这个 thymeleaf 代码:

<th:block th:each="item : ${menu}">
...
              <a th:href="@{/__${menu2}__/listagem}">
                  <i class="icon-asterisk"></i>
                  <span th:utext="${item}"></span>
              </a>
...
<th:block>

我尝试在单个循环th:each 中迭代两个列表(menumenu2)。对于menu2,我试试这个:

${menu2[itemStat.index]}

但我得到了错误:

org.springframework.expression.spel.SpelEvaluationException: EL1012E:(pos 5): Cannot index into a null value

在循环中访问第二个列表的正确方法是什么?

更新

  • 控制器:

    @ModelAttribute("menu")
    public List<String> menu() throws Exception {
        return ApplicationClasses.lista_classes_projeto();
    }
    @ModelAttribute("menu2")
    public List<Class<?>> menu2() throws Exception {
        return ApplicationClasses.lista_classes_projeto_2();
    }
    
  • 应用程序类:

    public static List<String> lista_classes_projeto() throws ClassNotFoundException {
    Locale currentLocale = Locale.getDefault();
        ResourceBundle messages = ResourceBundle.getBundle("messages", currentLocale);
    
    List<String> lista = new ArrayList<String>();
    
    ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(false);
    scanner.addIncludeFilter(new AnnotationTypeFilter(Form.class));
    for (BeanDefinition bd : scanner.findCandidateComponents("com.spring.loja.model")) {
      Class<?> clazz = Class.forName(bd.getBeanClassName());
      lista.add(messages.getString(clazz.getSimpleName()));
    }
    
    return lista;
    }
    
    public static List<Class<?>> lista_classes_projeto_2() throws ClassNotFoundException {
    List<Class<?>> lista = new ArrayList<Class<?>>();
    
    ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(false);
    scanner.addIncludeFilter(new AnnotationTypeFilter(Form.class));
    for (BeanDefinition bd : scanner.findCandidateComponents("com.spring.loja.model")) {
      Class<?> clazz = Class.forName(bd.getBeanClassName());
      lista.add(clazz);
    }
    
    return lista;
    }
    

【问题讨论】:

  • 向我们展示本节的完整代码,因为您目前存在差距,我们必须根据它们做出假设,例如itemStat 在哪里填充?该列表是否还包含数据的对象或非对象?
  • @Aeseir 该部分没有任何其他相关代码会改变对代码的理解。我将控制器中的 Java 代码添加到百里香代码迭代的数据源的问题中。

标签: spring loops spring-boot thymeleaf


【解决方案1】:

没有更多细节,我在提供这个答案时做出了很大的假设。

<block th:each="item,itemStat : ${menu}">
<span th:text="*{menu2[__${itemStat .index}__].something}"></span>  // assuming its a object that has parameter called somethin
</block>

我认为您的菜单 2 列表为空,因此也为空。

【讨论】:

  • 是的,我确认 menu2 在视图中为空(我不知道为什么)。从控制器中添加了带有数据源的 Java 代码(对于 menu 和 menu2 - menu 可以,但 menu2 不行,尽管几乎相同)。
  • 好的,我重新检查了代码,最后注意到我在错误的控制器中设置了属性model2。修复此问题后,代码可与 ${menu2[itemStat.index]} 一起使用
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-10-07
  • 2015-12-12
  • 2022-06-27
  • 2012-08-03
  • 2018-10-04
  • 2019-08-16
  • 1970-01-01
相关资源
最近更新 更多