简体   繁体   English

使用 twig 变量设置 chart.js 数据

[英]Use twig variable for setting chart.js data

i have an issue trying to get the twig values in the html and taking the data for a script that shows a pie chart with chart.js in the html我在尝试获取 html 中的树枝值并为脚本获取数据时遇到问题,该脚本在 html 中显示带有 chart.js 的饼图

This is how im adding the current project values from the db in the php controller这就是我如何从 php 控制器中的 db 添加当前项目值

$TEMPLATE_DATA['PROJECTS'] = $projects;

But the field with the data that i need is a json that look like this {"name":"test","size":"348"}但是包含我需要的数据的字段是一个 json,看起来像这样 {"name":"test","size":"348"}

So what i did in the html was doing a for loop for storing in a twig variable the array for that所以我在 html 中所做的是做一个 for 循环,用于将数组存储在一个树枝变量中

{% set brands = [] %}
{% for project in PROJECTS %}

    {% if project.name %}
    {% set brands = brands|merge([project.name]) %}
    {% endif %}
{% endfor %}

{% for brand in brands %}
   {{ brand |json_encode}}
{% endfor %}

this only gets the current names for the projects but ive also need other data from that json, the problem comes when i need to set the data variables for the chart, this is the script这只会获取项目的当前名称,但我还需要来自该 json 的其他数据,当我需要为图表设置数据变量时出现问题,这是脚本

<script>

var foo ='{{ brands |json_encode }}';
console.log(foo);

 console.log(typeof(foo));
// console.log(foo);

var data = {
    labels: [
        "Project 1",
        "Project 2",

        "Remaining"
    ],
    datasets: [
        {
           
            // data: [30, 40, 13],
            data: foo,

            backgroundColor: [
            "#FF6384",
                "#36A2EB",
                // "#FFCE56",
                // "#9861B1",
                // "#007D6F",
                // "#FF5D4D",
                // "#3B4856",
                "#9FADBD"
            ],
            hoverBackgroundColor: [
                "#FF6384",
                "#36A2EB",
                // "#FFCE56",
                // "#9861B1",
                // "#007D6F",
                // "#FF5D4D",
                // "#3B4856",
                "#9FADBD"
            ]
        }]
};
var ctx = document.getElementById("myChart");
var options = {
  responsive: true,
        legend: {
          position: 'bottom'
        },
  // tooltips: {
  //       callbacks: {
  //           label: function(tooltipItem) {
  //               return "%" + Number(tooltipItem.yLabel) + " usage";
  //           }
  //       }
  //   },
  tooltips: {
        enabled: true,
        mode: 'single',
        callbacks: {
            title: function (tooltipItem, data) { 
                return " " + data.labels[tooltipItem[0].index]; 
            },
            label: function(tooltipItem, data) {
          return data['datasets'][0]['data'][tooltipItem['index']] + " Kb";
        },
            
            // label: function(tooltipItems, data) {
            //     return "Total usage: " + tooltipItems.yLabel + ' €';
            // },
            // footer: function (tooltipItem, data) { return "..."; }
        }
    },
  plugins: {
    datalabels: {
      formatter: (value, ctx) => {

        let sum = ctx.dataset._meta[0].total;
        let percentage = (value * 100 / sum).toFixed(2) + "%";
        return percentage;


      },
      color: '#fff',
    }
  }
};
var myPieChart = new Chart(ctx,{
    type: 'pie',
    data: data,
    options: options
});
</script>

But at the end i just getting an a String and not a array of the names, and i cant find a way of using that data to use it in the current chart但最后我只得到一个字符串而不是名称数组,我找不到使用该数据在当前图表中使用它的方法

Easiest solution to your problem would be to use |解决您的问题最简单的方法是使用| json_encode pipe in twig, and parse it into JSON with JSON.parse to a javascript variable. json_encode管道,并使用JSON.parse将其解析为 JSON 到 javascript 变量。 Here's a brief example:下面是一个简短的例子:

const dataAsJson = JSON.parse({{ brands |json_encode }});

Add backticks if needed.如果需要,添加反引号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM