使用 thymeleaf 直接渲染视图片段

Render view fragments directly, using thymeleaf

我试图从模板中获取视图(片段)的一部分,但我最终收到以下错误

org.thymeleaf.exceptions.TemplateInputException: Error resolving template "path/to/template::fragment", template might not exist or might not be accessible by any of the configured Template Resolvers

这是当前配置:

TemplateResolver resolver = new ServletContextTemplateResolver();
resolver.setTemplateMode("HTML5");
resolver.setPrefix("/WEB-INF/templates/");
resolver.setCharacterEncoding("UTF-8");
resolver.setSuffix(".html");
resolver.setCacheable(false);
engine = new TemplateEngine();
engine.setTemplateResolver(resolver);

这听起来是可能的,因为它是作为一个功能给出的(但使用 spring-mvc,我不是):

http://www.thymeleaf.org/whatsnew21.html#spfrag

站点应用程序使用 jsp 运行,失败的代码如下所示:

render("surveys/survey", params,request,response);//This works
render("surveys/survey::surveyBody", params,request,response);//This fails

public static String render(String template,Map<String,?> context,HttpServletRequest request, HttpServletResponse response){
    IContext iContext = new WebContext(request,response,request.getServletContext(),Locale.US, context);
    return engine.process(template, iContext);
}

模板里面有这样的东西

<div th:fragment="surveyBody">
        <div th:each="field,idx : ${survey.fields}" th:id="${'field_' + field.id}" th:class="${field.type + ' row outter'}">
            <input type='hidden' th:id="${'field_' + field.id + '_id'}" id='field_100_id' value='100' />
            <input type='hidden' th:id="${'field_' + field.id + '_type'}" id='field_100_type' th:value='${field.type}' />
            <input type='hidden' th:id="${'field_' + field.id + '_order'}" id='field_100_order' th:value='${field.obj.order}' />
            <input type='hidden' th:id="${'field_' + field.id + '_outstanding'}" id='field_100_outstanding' value='-1' />
            <h3 th:utext="${field.obj.title[0].title}">title</h3>
            <h4 th:if="${!field.obj.subTitle.isEmpty()}" th:utext="${field.obj.subTitle[0].title}">subtitle</h4>
            <div class="answers row">
                <div th:replace="surveys/questions::${field.type}(${field},${disabled},${idx.index})"></div>
        </div>
    </div>
</div>

th:fragment 在模板中使用 th:replaceth:include 调用属性。

尝试创建一个清晰的文件(surveys/surveyfragment)并在其中写入:

<div th:replace="surveys/survey::surveyBody"/>

然后调用它:

render("surveys/surveyfragment", params,request,response);

应该可以