You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Thymeleaf中th:each循环渲染的<div>标签提交表单后返回页面消失的问题解决

Troubleshooting Disappearing Thymeleaf Loop Content After Form Submission

Hey there, let's break down why your wrap ingredients vanish after form submission and fix this step by step:

1. The #1 Culprit: Missing Model Data in Your POST Controller

Thymeleaf can only render the th:each loop if the ${wrap} variable exists in the model. When you submit the form and return the design view, you're probably not re-adding the wrap ingredient data to the model—so the loop has nothing to iterate over, hence it disappears entirely.

Take a look at your POST handler method. It might look like this right now:

@PostMapping("/design")
public String processTaco(@ModelAttribute Taco taco) {
    // Your taco processing logic here
    return "design"; // No model data repopulated!
}

You need to re-fetch and add the wrap ingredients back to the model before returning the view. For example, if you're using a repository:

@PostMapping("/design")
public String processTaco(@ModelAttribute Taco taco, Model model) {
    // Process the submitted taco...
    // Re-add wrap ingredients to the model
    model.addAttribute("wrap", ingredientRepository.findByType("WRAP"));
    return "design";
}

Double-check that the attribute name (wrap) matches exactly what's in your template—case sensitivity matters here!

2. Fix Your Form Field Binding (Bonus Critical Fix)

While this isn't directly causing the loop to disappear, your current checkbox setup won't submit selected ingredients to the backend. You're missing the name attribute, and you should use Thymeleaf's th:field to properly bind to your Taco object.

Assuming your Taco class has a List<String> ingredients field to store selected ingredient IDs, update your checkbox code like this:

<div th:each="ingredient:${wrap}">
    <input type="checkbox" th:field="*{ingredients}" th:value="${ingredient.id}"/>
    <span th:text="${ingredient.name}">INGREDIENT</span>
</div>

This ensures selected ingredients are bound to your Taco object on submission, which is the proper Thymeleaf way to handle form inputs.

3. Check for Silent Exceptions

If the above doesn't work, scan your server logs for any hidden exceptions. Sometimes an error processing the Taco object can prevent the model from being populated correctly, even if the page loads without obvious errors.

Quick Recap

  • Always repopulate dynamic data (like your wrap ingredients) in the POST controller before returning the view.
  • Ensure model attribute names match exactly what's referenced in your Thymeleaf template.
  • Fix form field binding to make your submission work as intended.

内容的提问来源于stack exchange,提问作者Hooman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 04:12:46