0

Controller has below defination:

@Controller
public class GreetingController {
    @GetMapping("/index")
    public String greeting(@RequestParam(name="name", required=false, defaultValue="World") String name, Map<String, Object> model) {
        String[] dataa = {"RTN", "YTN", "MTS", "RTS", "STS", "WTS"};
        System.out.println(name);
        model.put("message", "Hello world!");
        model.put("datta", dataa);
        return "index";
    }
}

Index.html has the code as below,

<script src="http://cdn.jsdelivr.net/webjars/jquery/2.1.4/jquery.min.js"></script>
    <script>
        var datass = /*[(${datta})]*/ [];
        var message = "[[${message}]]";
    </script>
    <script src="/js/script.js"></script>

Here I am trying to get the array to script.js file, I am not able to get the array. But in th:each in template the data is rendering properly. So I am missing something on passing data to js file. Any suggestions.

1

1 Answer 1

1

For using thymeleaf with your javascript code, you need to use

th:inline="javascript"

So the correct way would be like this -

<script th:inline="javascript">
    // your code
     var message = "[[${message}]]";

</script>

Look at this example, this is something you're looking for - https://attacomsian.com/blog/thymeleaf-set-javascript-variable#

1
  • In this case I am getting both message and "datass" undefined. If I am not using th:inline, atleast I am getting message in external js file. Also here the situation is trying to pass array. Commented Jul 9, 2020 at 8:29

Not the answer you're looking for? Browse other questions tagged or ask your own question.