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#

Sign up to request clarification or add additional context in comments.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.