使用百里香叶直接渲染视图片段

时间:2015-01-15 23:49:49

标签: 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>

1 个答案:

答案 0 :(得分:1)

使用 th:replace th:include 属性在模板中调用

:fragment

尝试创建一个清晰的文件( survey / surveyfragment )并写在那里:

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

然后叫它:

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

应该工作