Как отправить две серии из Flask на сюжет Чартиста. js - PullRequest
1 голос
/ 27 февраля 2020

Я хочу сравнить результаты 2019 года с результатами 2020 года. Для сравнения данных я создал диаграмму, используя Chartist.js; когда я использую только одну серию, отображается график (как видно на рисунке); Однако, когда я отправляю две серии, я не получаю график. Почему-то кажется, что инструкции в jinja2 не верны. Любая рекомендация, где ошибка в моем коде, будет очень полезна.

enter image description here

Исходный код для получения графика с использованием серии [100,200,300] выглядит так: следующим образом:

@app.route('/chart')
def chart():
    labels = ["Jan", "Feb", "Mar"] 
    series =  [100, 200, 300]          
    return render_template('chart.html',labels=labels, series=series)

Файл диаграммы. html выглядит следующим образом:

<!DOCTYPE html>
<html>
<head>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/chartist.js/latest/chartist.min.css">
  <script src="https://cdn.jsdelivr.net/chartist.js/latest/chartist.min.js"></script>
</head>

<style>
  body {
    background-color: #222;
    padding: 20px;
    font-family: arial;
  }

  #chart4 {
    background-color: slategrey;
    border-radius: 10px;
    padding-top: 10px;
  }

  #title{
    color:slategrey;
    margin-bottom: 10px;
  }


  /* Customizing plain Css:  */


  /* First series a */

  .ct-series-a .ct-line {
    stroke: black;
    stroke-width: 4px;
  }

  .ct-series-a .ct-point {
    stroke: red;
    stroke-width: 14px;
  }


  /* Second series b */

  .ct-series-b .ct-line {
    stroke: Orange;
    stroke-width: 4px;
  }

  .ct-series-b .ct-point {
    stroke: black;
    stroke-width: 14px;
  }

  /* Custom Css for the labels */

  #labels{
    padding-top:10px;
    display;block;
    height: 30px;
    width: 100%;
    border-radius:4px;
    margin-bottom: 10px;
    background-color: slategrey;
    text-align:center;
  }

  #series-b{
    float:right;
  }


  .label-series-a{
    stroke:black;
    fill:orange;
    stroke-width: 4px;
  }

  .label-series-b{
    stroke:red;
    fill:black;
    stroke-width: 4px;
  }


</style>

<body>
  <div id="title">Comparative analytics between 2019 and 2020:</div> 
  <div id="labels"> 2019: <svg width="14" height="14" viewBox="0 0 14 14" xmlns="http://www.w3.org/2000/svg">
    <rect x="0" y="0"
          width="14" height="14"
          rx="2" ry="2"
          class="label-series-b"
          />
  </svg> 
  &nbsp;&nbsp;2020:
      <svg width="14" height="14" viewBox="0 0 14 14" xmlns="http://www.w3.org/2000/svg">
    <rect x="0" y="0"
          width="14" height="14"
          rx="2" ry="2"
          class="label-series-a"
          />
  </svg>

  </div>

  <div id="chart4" class="ct-chart"></div>  


<script>
    var data = {
        // A labels array that can contain any sort of values
        // labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'],
        labels: [{% for item in labels %}
                    "{{ item }}",
                {% endfor %}],
        // Our series array that contains series objects or in this case series data arrays

        series: [ [{% for item in series %} 
                    "{{ item }}", 
                   {% endfor %}]
                ]
    };

      var options = {
          width: "640px",
          height: "320px"
      }

      // Create a new line chart object where as first parameter we pass in a selector
      // that is resolving to our chart container element. The Second parameter
      // is the actual data object.
      new Chartist.Line('#chart4', data);
</script>

путем изменения моего кода в @ app.route ('/ chart ') с двумя сериями [[100, 200, 300], [10,20,30]]

@app.route('/chart')
def chart():
   labels = ["Jan", "Feb", "Mar"] 
   series =  [[100, 200, 300],[10,20,30]]          
   return render_template('chart.html',labels=labels, series=series)

и внесением изменений в файл диаграммы. html в jinja2 (как указано в следующем код):

    <script>
    var data = {
        // A labels array that can contain any sort of values
        // labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'],
        labels: [{% for item in labels %}
                    "{{ item }}",
                {% endfor %}],
        // Our series array that contains series objects or in this case series data arrays
        series: [ [{% for item in series %} 
                    "{{ item }}", 
                   {% endfor %}],

                   [{% for item in series %} 
                   "{{ item }}", 
                    {% endfor %}]
               ]
    };

      var options = {
          width: "640px",
          height: "320px"
      }

      // Create a new line chart object where as first parameter we pass in a selector
      // that is resolving to our chart container element. The Second parameter
      // is the actual data object.
      new Chartist.Line('#chart4', data);
</script>

Я получаю график без построения трендовых линий. Где в коде на диаграмме. html Я делаю ошибку с jinja2?

Если я жестко закодировал серию, например [[1,2,3], [3,2,1]] в тег скрипт я получаю график правильно. Что говорит о том, что проблема в кодировке jinja2 на странице html. Я до сих пор не понимаю, в чем причина, любые предложения будут оценены.

    <script>
    var data = {
        // A labels array that can contain any sort of values
        // labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'],
        labels: [{% for item in labels %} "{{ item }}", {% endfor %}],
        // Our series array that contains series objects or in this case series data arrays
        series: [ 
                [1,2,3],
                [3,2,1]
        ]
    };

      var options = {
          width: "640px",
          height: "320px"
      }

      // Create a new line chart object where as first parameter we pass in a selector
      // that is resolving to our chart container element. The Second parameter
      // is the actual data object.
      new Chartist.Line('#chart4', data);
    </script>

enter image description here

1 Ответ

0 голосов
/ 27 февраля 2020

Это проще, чем вы думаете.
Кроме того, вам не нужны кавычки вокруг {{ item }} для серии.
Попробуйте:

    var data = {
        labels: [   {% for item in labels %}
                        "{{ item }}",
                    {% endfor %}
                ],
        series: [   {% for item in series %} 
                        {{ item }}, 
                    {% endfor %}
                ]
    };

enter image description here

...