Search code examples
javaspringspring-bootthymeleaf

Thymeleaf: could not parse as expression for links


I'm new to thymeleaf, and don't understand this error.

2020-04-16 16:20:24.222 ERROR 18060 --- [nio-8080-exec-1] org.thymeleaf.TemplateEngine : [THYMELEAF][http-nio-8080-exec-1] Exception processing template "products": Could not parse as expression: "/@{'/edit/' + ${product.id}}" (template: "products" - line 32, col 24)

org.thymeleaf.exceptions.TemplateProcessingException: Could not parse as expression: "/@{'/edit/' + ${product.id}}" (template: "products" - line 32, col 24)

here is the html/thymeleaf code:

    <tr th:each="product : ${products}">
        <td th:text="${product.id}">Product ID</td>
        <td th:text="${product.name}">Name</td>
        <td th:text="${product.brand}">Brand</td>
        <td th:text="${product.madein}">Made in</td>
        <td th:text="${product.price}">Price</td>
        <td>
            <a th:href="/@{'/edit/' + ${product.id}}">Edit</a>
            &nbsp;&nbsp;&nbsp;
            <a th:href="/@{'/delete/' + ${product.id}}">Delete</a>
        </td>
    </tr>

Here is the applicable Spring Boot Controller code:

@RequestMapping("/edit/{id}")
public ModelAndView showEditProductPage(@PathVariable(name = "id") int id) {
    ModelAndView mav = new ModelAndView("edit_product");
    Product product = productService.get(id);
    mav.addObject("product", product);

    return mav;
}

@RequestMapping("/delete/{id}")
public String deleteProduct(@PathVariable(name = "id") int id) {
    productService.delete(id);
    return "redirect:/";       
}

If I comment out the last td section, the rest of it works fine. Any suggestions?


Solution

  • Try to use following:

    <tr th:each="product : ${products}">
        <td th:text="${product.id}">Product ID</td>
        <td th:text="${product.name}">Name</td>
        <td th:text="${product.brand}">Brand</td>
        <td th:text="${product.madein}">Made in</td>
        <td th:text="${product.price}">Price</td>
        <td>
            <a th:href="@{/edit/{id}(id=${product.id})}">Edit</a>
            &nbsp;&nbsp;&nbsp;
            <a th:href="@{/delete/{id}(id=${product.id})}">Delete</a>
        </td>
    </tr>
    

    See the syntax here