Search code examples
javaspringspring-boottemplatesthymeleaf

Spring Boot - Thymeleaf and Json Templates


I am using Spring Boot 2.1.5.RELEASE and want to use Thymeleaf to generate JSON template files.

Here is an example of one of the files I currently have:

 {
  "apiVersion": "apps/v1",
  "kind": "Deployment",
  "metadata": {
    "labels": {
      "run": "[( ${imageNameLabel} )]"
    },
    "name": "[( ${imageNameLabel} )]"
  },
  "spec": {
    "replicas": [( ${replicas} )],
    "selector": {
      "matchLabels": {
        "run": "[( ${imageNameLabel} )]"
      }
    },
    "template": {
      "metadata": {
        "labels": {
          "run": "[( ${imageNameLabel} )]"
        }
      },
      "spec": {
        "containers": [
          {
            "image": "[( ${imageName} )]:[( ${imageVersion} )]",
            "name": "[( ${imageNameLabel} )]",
            "env": [( ${credentials} )],
            "volumeMounts": [
                            {
                                "mountPath": "/etc/foo",
                                "name": "[( ${imageNameLabel} )]",
                                "readOnly": true
                            }
                        ]
          }
        ],
        "volumes": [
                    {
                        "name": "[( ${imageNameLabel} )]",
                        "secret": {
                            "secretName": "[( ${imageNameLabel} )]"
                        }
                    }
                ]
      }
    }
  }
}

I want to put conditional logic into this file. Is this possible with Thymeleaf or is there another templating technology I should be looking at?


Solution

  • See the documentation for the textual template mode. An example if might look like:

    [# th:if="${condition}" th:text="${item}" /]
    

    Or

    [# th:if="${condition}"][(${imageNameLabel})][/]