Using Thymeleaf in order to generate inline json in the html view.

classic Classic list List threaded Threaded
3 messages Options
Reply | Threaded
Open this post in threaded view
|

Using Thymeleaf in order to generate inline json in the html view.

balteo
Hello,

I use Thymeleaf and Spring.

I have a "java.util.Set<Postcode> postcodes" available as a variable in my model and I need to be able to generate a JSon array that will be available in my html view as follows:

	<script type="text/javascript">
		$(document).ready(function() {
			var data = [
				 {id: 1, text: "75001"},
				 {id: 2, text: "75002"},
				 {id: 3, text: "75003"},
				 {id: 4, text: "75004"}
			];
		}
	</script>

I am not sure how to generate this with the th:each. Does Thymleaf offer an alternative?

Regards,

Julien.
Reply | Threaded
Open this post in threaded view
|

Re: Using Thymeleaf in order to generate inline json in the html view.

eiryu
I tried this. I used javascript inlining and List<Map<String, String>>.

controller
Map<String, String>map= new HashMap<String, String>();
map.put("id", "1");
map.put("text", "75001");

Map<String, String>map2= new HashMap<String, String>();
map2.put("id", "2");
map2.put("text", "75002");

model.addAttribute("var", Arrays.asList(map,map2));

html
<script type="text/javascript" th:inline="javascript">
    var map = /*[[${var}]]*/ [];
</script>


generated html
<script type="text/javascript">
    var map = [{'id':'1','text':'75001'},{'id':'2','text':'75002'}];
</script>
Reply | Threaded
Open this post in threaded view
|

Re: Using Thymeleaf in order to generate inline json in the html view.

balteo
Thanks! I'll try that.
Regards,
J.