Search code examples
templatesvariablesthymeleafrefactoringglobal

Thymeleaf enums refactoring issues


I encountered difficulties while refactoring a template. I have many references to a limited number of enum values ​​in one template. (in a code snippet i indicated only a short part for clarity)

 <span th:if="${shipment.supplier == **T(com.example.backorderServer.model.Supplier).XXX**}"></span>
      </td><!--Shipped orders-->
      <td>
        <th:block th:if="${shipment.supplier == **T(com.example.backorderServer.model.Supplier).YYY**}">
          <span th:if="${shipment.status == **T(com.example.backorderServer.model.ShipmentStatus).PREPARED**}"></span>
          <span th:if="${shipment.status == **T(com.example.backorderServer.model.ShipmentStatus).SHIPPED**}"><input type="submit" value="&#8680;" th:formaction="@{/api/administration/modifyShipments/__${shipment.idFromSupplier}__/delivered}"></span>
        </th:block>
        <span th:if="${shipment.supplier == **T(com.example.backorderServer.model.Supplier).XXX**}"></span>
      </td><!--Action (Recieve to Reiven stock)-->
      <td>
        <span th:if="${shipment.supplier == **T(com.example.backorderServer.model.Supplier).YYY**}"></span>
        <th:block th:if="${shipment.supplier == **T(com.example.backorderServer.model.Supplier).XXX**}">

Difficulties arose when it was necessary to transfer enums to other packages. At the moment I see only 1 way to manually adjust the paths, which I would like to avoid. Intuitively, it begs to be specified something like variables in the template that would refer to the each enum value once. And in the future use them, and not a link like "T(com.example.backorderServer.model.Supplier).XXX"

supplierXXX = T(com.example.backorderServer.model.Supplier).XXX;

Tell me, please, are there any ways to implement this approach?

I tried to search for Thymeleaf global variables and found this example

<body th:with="supplierXXX=${T(com.example.backorderServer.service.model.Supplier).XXX}">

And it did the trick.

<th:block th:if="${shipment.supplier == supplierXXX}">

This work fine. But i managed to swap this way only referencies to 1 enum value. How can i expand this block to declare few variables?

<body th:with="supplierXXX=${T(com.example.backorderServer.service.model.Supplier).XXX}; supplierYYY=${T(com.example.backorderServer.service.model.Supplier).YYY}">

Snippet above didnt parse.


Solution

  • You'd have to use commas not semicolons. for documentation see https://www.thymeleaf.org/doc/tutorials/2.1/usingthymeleaf.html#local-variables

    An example:

    <body th:with="supplierXXX=${T(com.example.backorderServer.service.model.Supplier).XXX},
      supplierYYY=${T(com.example.backorderServer.service.model.Supplier).YYY}">