xcoder
xcoder

Reputation: 11

How to write to a variable using ejs?

I am using an ejs templating engine. An array is stored in system.os. It needs to be written to the osdata variable, so that later it can be used to build the digram on chart.js.

HTML:

<%= let osdata = user.name %> // doesn't work
<canvas id="deviceChart" width="400" height="300"></canvas>

JS:

var ctx = document.getElementById('deviceChart').getContext('2d');
var myChart = new Chart(ctx, {
    type: 'pie',
    data: {
        labels: ['Red', 'Blue', 'Yellow', 'Green'],
        datasets: [{
            label: ' всего ',
            data: osdata, //osdata
            backgroundColor: [
                'rgba(255, 99, 132)',
                'rgba(54, 162, 235)',
                'rgba(255, 206, 86)',
                'rgba(75, 192, 192)',
            ],  
            borderWidth: 1
        }]
    },
    options: {
        scales: {
            yAxes: [{
                ticks: {
                    beginAtZero: true
                }
            }]
        }
    }
});

Upvotes: 0

Views: 100

Answers (2)

Afrida Anzum
Afrida Anzum

Reputation: 573

This can be done by adding a div element then calling it inside the script like this :

HTML:

<div id="osData" data-os= <%= user.name %> ></div>
<canvas id="deviceChart" width="400" height="300"></canvas>

JS:

<script>
let osData = document.getElementById('osData').dataset.os;
console.log(osData) //check your data here
</script>

Here you're accessing the value as element.dataset.keyname and the keyname is the os including the prefix data-

Upvotes: 1

Sean
Sean

Reputation: 8036

If you need to create a variable that's meant to be accessible to javascript running client-side in the browser, you should use EJS to declare it in a <script> tag:

<script>let osdata = <%= user.name %>;</script>
<canvas id="deviceChart" width="400" height="300"></canvas>

Upvotes: 0

Related Questions