I want Thymeleaf to throw an exception if a variable used in a template is not found in the Context. It seems by default Thymeleaf will inject empty text in an HTML tag if the bound variable is not found in the Context. This seems dangerous as it essentially silently hides errors.
<div data-th-text="${amount}">Blah</div>
Code:
Context context = new Context();
// never set "amount" variable
Output:
<div></div>
I assumed there would be a "strict" mode where it would throw an exception with the variable name and additional context if the variable is not found in the Context. I've been searching stackoverflow and the API docs but cannot find anything like this. I thought of overriding the Context getVariable
so that it does a containsVariable
check, but I'm not sure if that has performance implications. Also, I cannot capture any metadata about where in the template it failed. Am I missing something obvious?
I'm using Thymeleaf as a standalone engine -- not as part of a web/spring app.
You can do this by taking advantage of th:assert
. If this assertion is not satisfied then thymeleaf will throw an exception during document processing and print a relevant error to know why it failed.
So your code will be
<div th:assert="${amount} != null" data-th-text="${amount}">Blah</div>
If context variable amount
is never set it would be null so then the assertion will fail which will produce the exception.