使用ChartJS的EJS标签?

k5hmc34c  于 2023-10-18  发布在  Chart.js
关注(0)|答案(3)|浏览(179)

是否可以使用EJS标签将数据添加到图形中?以下是我当前图表的数据:

var canvas = document.getElementById('myChart');
var data = {
    labels: ["One", "February", "March", "April", "May", "June", "July"],
    datasets: [
        {
            label: "My First dataset",
            backgroundColor: "rgba(255,99,132,0.2)",
            borderColor: "rgba(255,99,132,1)",
            borderWidth: 2,
            hoverBackgroundColor: "rgba(255,99,132,0.4)",
            hoverBorderColor: "rgba(255,99,132,1)",
            data: [10, 20, 81, 56, 55, 40],
        }
    ]
};

我想做这样的事情:

labels: ["<%= currentUser.datapoint1 %>", "<%= currentUser.datapoint2 %>", "<%= currentUser.datapoint3 %>"]

data: [<%= currentUser.datapoint10 %>, <%= currentUser.datapoint11 %>]

如何使用EJS标签填充图形数据?(注意:在需要生成图表之前,EJS标签信息已经被用户保存)

igetnqfo

igetnqfo1#

是的,您可以使用EJS标签或其他任何跨各种view JavaScript框架使用的类似标签(例如,meteor、ejs等中的空格键、空格键)。Chart.js是在运行时初始化的,所以它不知道数据是如何进入文件的(例如,它不知道.也不关心.你的JavaScript是预处理和生成的)。
标记本身的格式与存储数据的变量有关。我建议将labelsdata存储在数组中,并使用JSON.stringify()

// defined in your app
var labels = ['label 1', 'label 2', ...];
var data = [datapoint1, datapoint2, ...];

// in your EJS file.
var canvas = document.getElementById('myChart');
var data = {
  labels: <%- JSON.stringify(labels); %>,
  datasets: [
    {
      label: "My First dataset",
      backgroundColor: "rgba(255,99,132,0.2)",
      borderColor: "rgba(255,99,132,1)",
      borderWidth: 2,
      hoverBackgroundColor: "rgba(255,99,132,0.4)",
      hoverBorderColor: "rgba(255,99,132,1)",
      data: <%- JSON.stringify(data); %>,
    }
  ]
};
0ejtzxu1

0ejtzxu12#

最简单的方法是在EJS标签中使用JSON.stringify()。你可以做

labels: <%- JSON.stringify(data.labels); %>,
data: <%- JSON.stringify(data.datasets.data); %>

它基于data变量。因此,您可能需要相应地调整此代码。

fcwjkofz

fcwjkofz3#

举个例子,修改Google Chart Quickstart Example会有很大的帮助。我尝试了下面,没有运气。
两个文件:chart.js用于创建数据,chart.ejs模板用于渲染L:
以下是我到目前为止整理的内容:chart.js

import { dirname } from "path";
import express from "express"
import { fileURLToPath } from "url";
const __dirname = dirname(fileURLToPath(import.meta.url));
let myData = [
  ['Mushrooms', 3],
  ['Onions', 1],
  ['Olives', 1],
  ['Zucchini', 1],
  ['Pepperoni', 2],
  ['Pineapple',12],
  ['Green Peppers',22]
  ]
  
  let myGraph ={}
  myGraph.name="First Chart"
  myGraph.myData=myData

  const app = express();

  app.get('/', (req, res) => {
    const templatePath = __dirname+"/views/chart.ejs";
    res.render(templatePath,{ graphs: myGraph })
    
});

  app.listen(3000, () => {
    //openBrowser('http://localhost:3000');
    console.log("Server running on localhost:3000")
  });

chart.ejs

这是我到目前为止所拥有的:

<!DOCTYPE html>
<html lang="en">

</html>
<html>

<head>
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    <script type="text/javascript">
        google.charts.load('current', { 'packages': ['corechart'] });
        google.charts.setOnLoadCallback(drawGraphs);

        function drawGraphs() {
            appendDivToBody(graphs.name, 'width: 1200px; height: 500px');
        const graphs = <%= JSON.stringify(graphs) %>;
            graphs.forEach(g => {
              appendDivToBody(g.name, 'width: 1200px; height: 500px');
              drawGraph(g.name, g.myData);
            });
        }

        function drawGraph(graphName, graphData) {
            var data = new google.visualization.DataTable();
            data.addColumn('string', 'Toppings');
            data.addColumn('number', 'Slices');
            data.addRows(graphData);
            var options = {
                title: `${graphName}`,
                'width': 500,
                'height': 300
            };
            var chart = new google.visualization.PieChart(document.getElementById(graphName));
            chart.draw(data, options);
        }

        function appendDivToBody(id, style) {
            var div = document.createElement('div');
            div.id = id;
            div.style = style;
            document.getElementsByTagName('body')[0].appendChild(div);
        }

    </script>
</head>

<body>
    <% console.log(graphs.name) %>
    <% console.log(graphs.myData) %>

    <p>
        <!-- HTML content goes here -->
        Hello
    </p>
    <ul>
        <%graphs.myData.forEach((item)=> { %>
            <li>
                I had <%=item[1] %> slices of <%=item[0]%> pizza </br>
            </li>
            <%})%>
    </ul>

</body>
</body>

</html>

相关问题