Search code examples
thymeleaf

Thymeleaf - Set attribute in meta tag with conditional


I would like to set the content of my "robots" tag depending on an attribute returned with my model. In my back end return statements, I have one place where I return the following snippet, and some places where I do not set that attribute at all.

model.addAttribute("robotsMetaTag", "all");
return "pages/index";

I would like to make it so the attribute looks like this if I am setting robotsMetaTag:

<meta name="robots" content="all"/>

and like this if there robotsMetaTag is not set:

<meta name="robots" content="none"/>

Currently, I am doing the following:

<meta name="robots" th:attr="content=${robotsMetaTag}"/>

This works for the pages where I am returning a value for robotsMetaTag, but I would like a default case where if nothing is set/returned then I want the default to be "none". I've been trying to get th:attrappend to work for me for this, but I'm getting parsing errors with the following:

<meta name="robots" th:attrappend="content=${${robotsMetaTag} == null}?none:${robotsMetaTag}"/>

Any help would be greatly appreciated.


Solution

  • Try out this

    <meta name="robots" th:attr="content=${robotsMetaTag==null?'none':robotsMetaTag}"/>