Description:
I'm trying to initialize a JSON object into my javascript template.
View: views.tasks.task.js
@()
@import play.libs.Json
@import enums.TaskType
...
var taskTypes = @Html(@Json.stringify(TaskType.valuesJson()));
Model: TaskType
public enum TaskType {
@EnumValue("General")
GENERAL(1, "General", "label-info", "item-blue");
...
public static JsonNode valuesJson() {
ArrayNode arr = Json.newObject().arrayNode();
for(TaskType tt: values()){
arr.add(tt.jsonNode());
}
return arr;
}
Result:
taskTypes = [{\"value\":\"General\",\"label\":\"label-info\",\"itemColor\":\"item-blue\"}];
Expected:
taskTypes = [{"value":"General","label":"label-info","itemColor":"item-blue"}];
Question: How to do it without escaping? Why is @Html(...) not working?
Solution: @JavaScript(Json.stringify(TaskType.valuesJson()));
Explanation: Play use a JavaScript template format for files "*.js", so you need to use @JavaScript rather than @Html. It's clear after understanding how the templates engine works...
Sources: