Skip to main content

Chart Solution


Out chart solution is based on Chart.js, which is a lightweight library that is easy to use and requires minimal setup. It has a simple API and supports a wide range of chart types, including line, bar, pie, radar, and more.

A Stimulus controller chart_controller.ts is taking care of passing values from DOM element to Chart.js.

How to use

Example 1

We can set data attributes on the canvas element, to pass values to Chart.js directly.

data-chart-data-value='{ "labels": ["January", "February", "March", "April", "May", "June", "July"], "datasets": [{ "label": "My First dataset", "backgroundColor": "transparent", "borderColor": "#3B82F6", "data": [37, 83, 78, 54, 12, 5, 99] }] }'

Example 2

Or we can use Javascript

<div class="chart-container"></div>

const data = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [{
label: 'My First Dataset',
data: [65, 59, 80, 81, 56, 55, 40],
fill: false,
borderColor: 'rgb(75, 192, 192)',
tension: 0.1
const options = {

const container = document.querySelector('.chart-container');
const canvas = document.createElement("CANVAS");

canvas.setAttribute('data-controller', 'chart');
canvas.setAttribute('data-chart-type-value', 'line');
canvas.setAttribute('data-chart-data-value', JSON.stringify(data));
canvas.setAttribute('data-chart-options-value', JSON.stringify(options));

// Stimulus will use chart_controller to init the chart


To include data for Javascript in Django template, we can use json_script template tag.

{{ chart_data|json_script:"chartData" }}

const chartData = JSON.parse(document.getElementById('chartData').textContent);

And then we can set chartData on the data attributes of the canvas element to get the chart working.

Component Library

You can find some chart demos in the component library.


To customize the behavior, you can use inheritance to extend the Stimulus controller chart_controller.ts

For example, send Ajax request to get chart data from the backend.