List all available model attributes in Thymeleaf

The accepted answer does not seem to work for Thymeleaf 3; here's an update. Please note that I'm using Spring; this might not work for non-Spring apps.

<table>
    <tr th:each="var : ${#vars.getVariableNames()}">
        <td th:text="${var}"></td>
        <td th:text="${#vars.getVariable(var)}"></td>
    </tr>
    <!-- 
        Adding these manually because they are considered special.
        see https://github.com/thymeleaf/thymeleaf/blob/thymeleaf-3.0.3.RELEASE/src/main/java/org/thymeleaf/context/WebEngineContext.java#L199
    -->
    <tr>
        <td>param</td>
        <td th:text="${#vars.getVariable('param')}"></td>
    </tr>
    <tr>
        <td>session</td>
        <td th:text="${#vars.getVariable('session')}"></td>
    </tr>
    <tr>
        <td>application</td>
        <td th:text="${#vars.getVariable('application')}"></td>
    </tr>
</table>

That said, what I've done is created a standalone Bean that makes things a bit prettier and dumps to logs instead of to HTML:

@Component
public class ThymeleafDumper {

    private Logger log = LoggerFactory.getLogger(ThymeleafDumper.class);

    public void dumpToLog(WebEngineContext ctx) {
        log.debug("Thymeleaf context: {}", formatThisUpNicely(ctx));
    }

    // ... etc
}

Where formatThisUpNicely can use ctx.getVariableNames(), put the results into a SortedMap, export to json, whatever. Don't forget those three 'special' variables!

Then expose an instance of it as a @ModelAttribute in a Controller or a ControllerAdvice:

@ControllerAdvice
public class SomeControllerAdvice {

    @Autowired
    private ThymeleafDumper thymeleafDumper;

    @ModelAttribute("dumper")
    public ThymeleafDumper dumper() {
        return this.thymeleafDumper;
    }
}

Then in my template run:

<div th:text="${dumper.dumpToLog(#vars)}"/>

Try this:

<table>
    <tr th:each="var : ${#vars}">
        <td th:text="${var.key}"></td>
        <td th:text="${var.value}"></td>
    </tr>
</table>

these are all the logging available configurations :

log4j.logger.org.thymeleaf=DEBUG
log4j.logger.org.thymeleaf.TemplateEngine.CONFIG=DEBUG
log4j.logger.org.thymeleaf.TemplateEngine.TIMER=DEBUG
log4j.logger.org.thymeleaf.TemplateEngine.cache.TEMPLATE_CACHE=DEBUG
log4j.logger.org.thymeleaf.TemplateEngine.cache.FRAGMENT_CACHE=DEBUG
log4j.logger.org.thymeleaf.TemplateEngine.cache.MESSAGE_CACHE=DEBUG
log4j.logger.org.thymeleaf.TemplateEngine.cache.EXPRESSION_CACHE=DEBUG

these will log all the thymeleaf actions. I hope it is helpful.

Tags:

Java

Thymeleaf