Using javascript in play template

前端 未结 2 717
一整个雨季
一整个雨季 2021-01-20 00:11

I\'m using the Play! Framework. And I have a scala.html template file.

I\'m trying to add a Google javascript library to add graphs to the Web app.

Basiclly

2条回答
  •  野的像风
    2021-01-20 00:33

    First thing: you should use your browser inspection tool to read the error(s) anyway, collecting data like this by simple loop isn't good idea as - as you can see you have an orphan comma char after last item - JavaScript doesn't accept this.

    The best option is building JSON object in the controller's action and then passing it as param to the view. It guarantees that you won't have any syntax errors, like orphan commas, unclosed brackets, etc. Also if no items it will generate valid JS code like
    var data = google.visualization.arrayToDataTable([]); (empty array)

    The Java pseudo code looks like this (of course in your case you need to iterate your collection to fill the myValues List

    public static Result chartData() {
    
        // For JS you need an array of arrays, so use a List of Lists in Java
        List> myValues = new ArrayList<>();
    
        // Add the header
        myValues.add(new ArrayList(Arrays.asList("Date", "Sale")));
    
        // Inserting dummy data, 
        // in this place you should iterate your `currentPage.getList()` instead
        myValues.add(new ArrayList(Arrays.asList("2010", 1000)));
        myValues.add(new ArrayList(Arrays.asList("2011", 1030)));
        myValues.add(new ArrayList(Arrays.asList("2012", 1530)));
        myValues.add(new ArrayList(Arrays.asList("2013", 3507)));
    
    
        // Convert the values to JSON 
        // and wrap it with play.twirl.api.Html, so you won't need to do this within the template
        Html chartData = new Html(Json.toJson(myValues).toString());
    
        return ok(views.html.myChart.render(chartData));
    }
    
    
    

    and your myChart.scala.html view

    @(chartData: Html)
    
    
    

    The result HTML code in browser is:

    
    

    提交回复
    热议问题