简体   繁体   中英

Add code into html head tag from variable with Thymeleaf (Spring)

I have a webapp written with Spring Boot and Thymeleaf. I need to dynamically add a custom "code" inside the HTML head tag. This custom "code" is stored inside a variable in the Spring model object. I tried many ways but none of them seem to work. These are all the ways I tested:

<head>
   #1 [[${headCode}]]
   #2 <div th:text="${headCode}"></div>
   #3 <span th:text="${headCode}"></span>
   #4 <div th:html="${headCode}"></div>
   #5 <div th:text="${headCode}" th:remove="tag"></div>
   #6 <div th:html="${headCode}" th:remove="tag"></div>
   #7 <span th:text="${headCode}" th:remove="tag"></span>
</head>

Example: Let say we have this Spring controller which put a particular code inside the model variable "headCode":

@GetMapping
public String getPage(Model model){
   String headCode = "<script>
        console.log('1');
        </script>
        <script>
        console.log('2');
        </script>
        <script>
        console.log('3');
        </script>"
   model.addAttribute("headCode", headCode);
   return "page";
}

I would like, inside the rendered html page, to have something like this:

<html>
<head>
   [head content]
   <script>
        console.log('1');
   </script>
   <script>
        console.log('2');
   </script>
   <script>
        console.log('3');
   </script>
</head>
<body>
   [body content]
</body>
</html>

I don't have a fixed code to had, I cannot hardcode it inside the head section, so I need to figure out a different way to insert it inside the head section. For instance this custom code could be the Facebook Pixel which I have to be able to change every time I need it. Any ideas?

Maybe you should try with a fragment that replace the whole header element and pass any variable you need in the fragment signature.

In the official docs, there is an example of this:

https://www.thymeleaf.org/doc/tutorials/2.1/usingthymeleaf.html#parameterizable-fragment-signatures

<header th:fragment="contentheader(title)" th:assert="${!#strings.isEmpty(title)}">...</header>

Hope this help!

Here is a working example of how to setup an endpoint, with data from the controller:

@GetMapping(VIEW_NAME)
  public ModelAndView viewPage() {
    ModelAndView modelAndView = new ModelAndView(VIEW_NAME);
    modelAndView.addObject("yourDto", new YourDto());
    return modelAndView;
  }

Your second try in the HTML code is correct, problem should be related to the string you were passing to the view in the controller. You should check the conditionals section of the Thymeleaf Docs Also you can download a working example their repository.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM