在播放模板中使用 javascript [英] Using javascript in play template

查看:19
本文介绍了在播放模板中使用 javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Play!框架.我有一个 scala.html 模板文件.

我正在尝试添加一个 Google javascript 库来向网络应用添加图表.

基本上需要用我自己的值填充以下函数:

function drawChart() {var 数据 = google.visualization.arrayToDataTable([['日期','销售'],['2004', 1000],['2005', 1170],['2006', 660],['2007', 1030]]);

所以我做了以下操作(这适用于 HTML 文件的其他部分,但不适用于 Javasript):

@for(run <- currentPage.getList) {[@run.date.format("dd MMM yyyy"),@run.sales],}

但是以@ 符号为前缀的 Scala 代码在 Javascript 中不起作用.

谁能给点建议?

谢谢.

完整代码如下:

@main {<h1 id="homeTitle">@Messages("runs.listRuns.title", currentPage.getTotalRowCount)</h1>@if(flash.containsKey("success")) {<div class="alert-message warning"><strong>完成!</strong>@flash.get("成功")

}<!-- 图表--><头><脚本类型=文本/javascript"src="https://www.google.com/jsapi?autoload={模块":[{'name':'可视化','版本':'1','包':['核心图']}]}"></script><script type="text/javascript">google.setOnLoadCallback(drawChart);函数 drawChart() {var 数据 = google.visualization.arrayToDataTable([['日期', '成功百分比'],@for(run <- currentPage.getList) {[@run.runDate.format("dd MMM yyyy"), @run.successPercentage],}]);变量选项 = {标题:无引擎性能监控",曲线类型:'功能',图例:{位置:'底部'}};var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));图表绘制(数据,选项);}<身体><div id="curve_chart" style="width: 80%; height: 500px"></div><!-- 图表--><div id="动作"><form action="@link(0, "name")" method="GET"><input type="search" id="searchbox" name="f" value="@currentFilter" placeholder="按运行名称过滤..."><input type="submit" id="searchsubmit" value="按运行名称过滤" class="btn primary"></表单>

解决方案

第一件事:无论如何,你应该使用浏览器检查工具来读取错误,通过简单的循环收集这样的数据并不是一个好主意,因为 -正如您所看到的,在最后一项之后有一个孤立的逗号字符 - JavaScript 不接受这一点.

最好的选择是在控制器的操作中构建 JSON 对象,然后将其作为参数传递给视图.它保证您不会有任何语法错误,例如孤儿逗号、未闭合的括号等.此外,如果没有项目,它将生成有效的 JS 代码,例如
var data = google.visualization.arrayToDataTable([]);(空数组)

Java 伪代码看起来像这样(当然在您的情况下,您需要迭代您的集合以填充 myValues List

public static 结果 chartData() {//对于 JS,你需要一个数组数组,所以在 Java 中使用 List of Lists列表<列表<对象>>myValues = new ArrayList<>();//添加标题myValues.add(new ArrayList(Arrays.asList("Date", "Sale")));//插入虚拟数据,//在这个地方你应该迭代你的 `currentPage.getList()`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)));//将值转换为 JSON//并用 play.twirl.api.Html 包装它,所以你不需要在模板中这样做Html chartData = new Html(Json.toJson(myValues).toString());返回 ok(views.html.myChart.render(chartData));}

和您的 myChart.scala.html 视图

@(chartData: Html)<脚本>var chartData = @chartData;控制台日志(图表数据);//或者在你的情况下...var 数据 = google.visualization.arrayToDataTable(@chartData);

浏览器中的结果 HTML 代码为:

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 Ineed to populate the follwoing function with my own values:

function drawChart() {
        var data = google.visualization.arrayToDataTable([
          ['Date', 'Sales'],
          ['2004',  1000],
          ['2005',  1170],
          ['2006',  660],
          ['2007',  1030]
        ]);

So I did the following (this works in other parts of the HTML file, but not within Javasript):

@for(run <- currentPage.getList) {
      [@run.date.format("dd MMM yyyy"),@run.sales],
                      }

But the Scala code that is prefixed with @ symbol is not working inside Javascript.

Can anyone please advise?

Thanks.

Here is the whole piece of code:

@main {

    <h1 id="homeTitle">@Messages("runs.listRuns.title", currentPage.getTotalRowCount)</h1>

    @if(flash.containsKey("success")) {
        <div class="alert-message warning">
            <strong>Done!</strong> @flash.get("success")
        </div>
    }


    <!-- CHART  -->
         <html>
          <head>
            <script type="text/javascript"
                  src="https://www.google.com/jsapi?autoload={
                    'modules':[{
                      'name':'visualization',
                      'version':'1',
                      'packages':['corechart']
                    }]
                  }"></script>

            <script type="text/javascript">
              google.setOnLoadCallback(drawChart);

              function drawChart() {
                      var data = google.visualization.arrayToDataTable([
                      ['Date', 'Success Percentage'],

                      @for(run <- currentPage.getList) {
                          [@run.runDate.format("dd MMM yyyy"), @run.successPercentage],
                      }

                  ]);



                var options = {
                  title: 'Engineless Performance Monitoring',
                  curveType: 'function',
                  legend: { position: 'bottom' }
                };

                var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));

                chart.draw(data, options);
              }
            </script>
          </head>
          <body>
            <div id="curve_chart" style="width: 80%; height: 500px"></div>
          </body>
        </html>
    <!-- CHART -->

    <div id="actions">    
        <form action="@link(0, "name")" method="GET">
            <input type="search" id="searchbox" name="f" value="@currentFilter" placeholder="Filter by Run Name...">
            <input type="submit" id="searchsubmit" value="Filter by Run Name" class="btn primary">
        </form>
    </div>

解决方案

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<List<Object>> myValues = new ArrayList<>();

    // Add the header
    myValues.add(new ArrayList<Object>(Arrays.asList("Date", "Sale")));

    // Inserting dummy data, 
    // in this place you should iterate your `currentPage.getList()` instead
    myValues.add(new ArrayList<Object>(Arrays.asList("2010", 1000)));
    myValues.add(new ArrayList<Object>(Arrays.asList("2011", 1030)));
    myValues.add(new ArrayList<Object>(Arrays.asList("2012", 1530)));
    myValues.add(new ArrayList<Object>(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)

<script>
    var chartData = @chartData;
    console.log(chartData);

    // Or in your case...
    var data = google.visualization.arrayToDataTable(@chartData);
</script>

The result HTML code in browser is:

<script>
    var chartData = [["Date","Sale"],["2010",1000],["2011",1030],["2012",1530],["2013",3507]];
    console.log(chartData);

    // Or in your case...
    var data = google.visualization.arrayToDataTable([["Date","Sale"],["2010",1000],["2011",1030],["2012",1530],["2013",3507]]);
</script>

这篇关于在播放模板中使用 javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆