Search code examples
thymeleafvariable-names

Dynamic variable name with dashes in thymeleaf


I am trying to create a variable name in thymeleaf by using another variable as prefix:

th:with="appOverview = ${__${tabId}__AppOverview}"

It works most of the times, but in the case where tabId contains dashes (i.e., "my-test-tab"), thymeleaf throws the following exception:

The operator 'SUBTRACT' is not supported between objects of type 'null' and 'null'

I guess that the dashes confuse thymeleaf into believing it's an arithmetic operation between non-existing variables.

I tested adding a variable with th:with="my-var='bad dashes'" and it worked fine, so I suppose dashes are generally accepted as characters in variable names.

Is there a way to tackle this issue?


Solution

  • Ah, I finally found it!

    The thing I was missing is that all model variables are stored in thymeleaf in the #vars object, so accessing them from there won't confuse thymeleaf. Here's what worked:

    th:with="appOverview = ${#vars.get('__${tabId}__AppOverview')}"