如何在Thymeleaf模板中迭代数组列表?

时间:2015-10-12 11:14:20

标签: iteration thymeleaf

我正在尝试从数组列表中写出项目并从中创建一个复选框。这个模板有什么问题?

模板 grant_access.html

<form action="#" th:action="@{/accounts/grant_access}" th:object="${request}" method="post">
        <div th:each="scope:${request.requestScopes}" class="checkbox">
            <label>
                <input type="checkbox" value="${scope.id}" />&nbsp;${scope.scope}

            </label>
        </div>
        <button type="submit" name="action" value="authorize" class="btn btn-default">Authorize</button>
        <button type="submit" name="action" value="cancel" class="btn btn-link">Cancel</button>
    </form>

这是输出,代码未转换为值。

<form action="/restapi/accounts/grant_access" method="post">
    <div class="checkbox">
        <label>
            <input type="checkbox" value="${scope.id}" />&nbsp;${scope.scope}
        </label>
    </div>
    <button type="submit" name="action" value="authorize" class="btn btn-default">Authorize</button>
    <button type="submit" name="action" value="cancel" class="btn btn-link">Cancel</button>
</form>

这是控制器和请求对象:

    @RequestMapping(value = "/grant_access", method = RequestMethod.GET)
    public ModelAndView authorize(HttpServletRequest httpServletRequest) {

List<Scope> scopes = scopeService.getRequestedScopes(authorizationRequest.getScope());

        GrantRequest request = new GrantRequest();
        request.setAccount(account);
        request.setClient(client);
        request.setRequestScopes(scopes);

        ModelAndView modelAndView = new ModelAndView("grant_access");
        modelAndView.addObject("request", request);

        return modelAndView;
}

和GrantRequest类:

public class GrantRequest {

    private Account account;
    private Client client;
    private ArrayList<Long> scopeIds;
    private List<Scope> requestScopes;
// getters and setters omitted...

}

1 个答案:

答案 0 :(得分:0)

您需要使用th:前缀,以便Thymeleaf实际处理属性:

<input type="checkbox" th:value="${scope.id}" />&nbsp;<span th:text="${scope.scope}" />

请注意,value现在是th:value${scope.scope}部分现在包含在范围内,因此可以处理它的值。