如何访问从javascript文件传递到html模板的变量?

时间:2018-08-07 02:44:57

标签: javascript html flask chart.js

我在Flask应用程序中使用Chart.js。我通过labels将变量legendvalueschart.html传递给render_template

我的应用程序正在使用以下chart.html:

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Chart</title>
    <script src='static/js/Chart.bundle.min.js'></script>
  </head>
  <body>
    <center>
      <h1>Simple Line Chart</h1>
      <canvas id="bar-chart" width="300" height="200"></canvas>
    </center>
    <script>
      new Chart(document.getElementById("bar-chart"), {
        type: 'bar',
        data: {
          labels : [{% for item in labels %}
                   "{{item}}",
                  {% endfor %}],
          datasets: [
            {
              label: '{{ legend }}',
              backgroundColor: ["#3e95cd", "#8e5ea2","#3cba9f","#e8c3b9","#c45850"],
              data : [{% for item in values %}
                      {{item}},
                    {% endfor %}]
            }
          ]
        },
        options: {
          legend: { display: true },
          title: {
            display: true,
            text: 'Test Chart'
          },
          scales: {
            yAxes: [{
              ticks: {
                beginAtZero:true
              }
            }]
          }
        }
    });
    </script>
</body>
</html>

我想将脚本节分成一个单独的文件,但是当我将<script></script>标签内的节粘贴到文件bar-chart.js时,出现错误:

Uncaught SyntaxError: Unexpected token %

bar-chart.js的第4行,如下所示:

labels : [{% for item in labels %}

这是我尝试使用的经过修订的chart.html和bar-chart.js:

bar-chart.js:

new Chart(document.getElementById("bar-chart"), {
        type: 'bar',
        data: {
          labels : [{% for item in labels %}
                   "{{item}}",
                  {% endfor %}],
          datasets: [
            {
              label: '{{ legend }}',
              backgroundColor: ["#3e95cd", "#8e5ea2","#3cba9f","#e8c3b9","#c45850"],
              data : [{% for item in values %}
                      {{item}},
                    {% endfor %}]
            }
          ]
        },
        options: {
          legend: { display: true },
          title: {
            display: true,
            text: 'Test Chart'
          },
          scales: {
            yAxes: [{
              ticks: {
                beginAtZero:true
              }
            }]
          }
        }
    });

chart.html:

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Chart</title>
    <script src='static/js/Chart.bundle.min.js'></script>
  </head>
  <body>
    <center>
      <h1>Simple Line Chart</h1>
      <canvas id="bar-chart" width="300" height="200"></canvas>
    </center>
    <script type="text/javascript" src='static/js/charts/bar-chart.js'></script>
      </body>
    </html>

如何从Javascript文件中成功调用变量labelslegendvalues

0 个答案:

没有答案