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

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

问题描述

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

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

我正在尝试添加一个Google javascript库,以便将图形添加到Web应用程序中。

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

Basiclly Ineed用我自己的值填充以下函数:

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]
        ]);

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

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],
                      }

但是Scala代码带有@符号前缀的内容在Javascript中无效。

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

任何人都可以提供建议吗?

Can anyone please advise?

谢谢。

以下是整段代码:

@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>


推荐答案

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

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.

最好的选择是在控制器的动作中构建JSON对象,然后将其作为参数传递给视图。它保证你不会有任何语法错误,如孤立逗号,未闭合括号等。如果没有项目,它将生成有效的JS代码,例如

var data = google。 visualization.arrayToDataTable([]); (空数组)

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)

Java伪代码看起来像这样(当然在你的情况下你需要迭代你的集合来填充 myValues 列表

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));
}

以及 myChart.scala.html 视图

@(chartData: Html)

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

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

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

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天全站免登陆