Search code examples
thymeleaf

Render view fragments directly, using thymeleaf


I am trying to get just a part of the view(fragment) from a template, i just end up getting the following error

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

And this is the current configuration:

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);

It soud be possible as it is given as a feature(but using spring-mvc, which I am not):

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

The site application works using jsp, and the code that is failing looks like this:

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);
}

inside the template there is something like this

<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>

Solution

  • th:fragment is called in template using th:replace or th:include attributes.

    Try to create a clear file (surveys/surveyfragment) and write there:

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

    And then call it:

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

    Should work