0

I'm trying to pass a twig table with "for" function into JS.

<script type="text/javascript">
        google.charts.load('current', {'packages':['corechart']});
        google.charts.setOnLoadCallback(drawChart);

        function drawChart() {

            var data = google.visualization.arrayToDataTable([
            ['Kategoria', 'Kwota'],            
                {% for user_expense in user_expenses %}
                    ['user_expense.category', 'user_expense.sum'];
                {% endfor %}
            ]);

            var options = {
            title: 'Wydatki'
            };

            var chart = new google.visualization.PieChart(document.getElementById('expense_chart'));

            chart.draw(data, options);
        }
    </script>

I tried doing it this way, but it doesn't work. Is there any way to do that?

WhiteHat
  • 59,912
  • 7
  • 51
  • 133
  • wouldn't recommend manually building the json in that way. instead, separate the pages. one page which simply writes the data from twig using --> `{{ user_expense|json_encode() }}` -- the other page with the html / javascript, using ajax to get data from twig page. -- [here is a php example which would be similar](https://stackoverflow.com/a/62063641/5090771) – WhiteHat Sep 13 '22 at 20:17
  • @WhiteHat Thanks, that actually helped me a lot. Although I've done it this way: `function drawChart() { expenses = {{ user_expense|json_encode()|raw }}; var data = google.visualization.arrayToDataTable(expenses); var options = { title: 'Wydatki' }; var chart = new google.visualization.PieChart(document.getElementById('expense_chart')); chart.draw(data, options); }` due to using MVC framework. I had no idea how to transfer predefined variables used in sql query but this one works too. – The Napioor Sep 13 '22 at 21:06
  • cheers! that should work fine. the only drawback is you can't refresh the data / chart, without refreshing the page... – WhiteHat Sep 14 '22 at 14:05

0 Answers0