Thymeleaf表达式解析错误:分页模板代码报错求助
Hey there, let's sort out that Thymeleaf parsing error you're facing with your pagination code. The root cause is how you're embedding Thymeleaf variables into the JavaScript function call in your th:href attribute—using backticks `${previous}` doesn't play nice with Thymeleaf's expression parser.
Here's the corrected code with two solid approaches:
Approach 1: String concatenation with Thymeleaf variable substitution
Wrap the Thymeleaf variable in single quotes (since the th:href attribute uses double quotes) to properly pass the value to your movePage function:
<ul class="results_perpage" > <li th:if="${previous != null}"> <a th:href="javascript:movePage('${previous}');" class="results_menu" th:text="PREVIOUS"></a> </li> <li><a href="#" class="results_menu" th:text="${numPage}"></a></li> <li> <a th:href="javascript:movePage('${next}');" class="results_menu" th:text="NEXT"></a> </li> </ul>
Approach 2: Use Thymeleaf inline expressions (cleaner syntax)
Thymeleaf's inline expression syntax [[${variable}]] is designed for embedding values into text/script contexts, making this easier to read and less error-prone:
<ul class="results_perpage" > <li th:if="${previous != null}"> <a th:href="javascript:movePage('[[${previous}]]')" class="results_menu" th:text="PREVIOUS"></a> </li> <li><a href="#" class="results_menu" th:text="${numPage}"></a></li> <li> <a th:href="javascript:movePage('[[${next}]]')" class="results_menu" th:text="NEXT"></a> </li> </ul>
Note: If previous/next are numeric values, you can omit the single quotes around the inline expression.
Quick additional checks:
- Make sure your
movePage()JavaScript function is defined somewhere in your page (Thymeleaf parsing success doesn't guarantee the function exists!). - Verify that
previous,numPage, andnextare correctly populated in your backend Model (you already handlepreviousbeing null withth:if, which is good!).
内容的提问来源于stack exchange,提问作者Salvador Borés

