Tobiasz Dziubinski
Tobiasz Dziubinski

Reputation: 53

Create javascript variable with thymeleaf

I need to visualize some data and I want to create an javascript array based on this data.

I want to inject my own name and data to a variable from java code

/*[+
           var [+ [[${data.getDataName}]] =  [[${data.getData()}]];
+]*/

However name and data appears in brackets. Is there any walk around? Maybe you can recommend better html template engine, which works better with javascript?

Right now I have hard-coded html and javascript in my code and I want to get rid of it.

Upvotes: 1

Views: 1139

Answers (1)

xdhmoore
xdhmoore

Reputation: 9876

Probably solved this by now, but I'll give it a shot anyway...

I'm not sure I understand the [+ syntax, but other than that:

You probably don't want to dynamically name variables, unless you're writing your own framework or something. It will be harder for someone else to read. Also, explicitly defining variable names isn't usually considered 'hard-coding'. However, if you do want to write your own mini-framework, you could try something crazy, like the following:

var data = {};
var name = /*[[${data.getDataName()}]]*/ '';
var value = /*[[${data.getData()}]]*/ '';

data[name] = value;

However, you could also initialize a series of pairs like so: [['name1', 'value1'],['name2', 'value2'], ['name3', 'value3']]. Maybe this is what you want. Probably the easiest way to do this would be to define it in Java (as a List<Pair<String>> or something. Or you could use a List instead of a Pair, if you don't have one and don't feel like making one.

Upvotes: 1

Related Questions