user6047666
user6047666

Reputation:

How to pass a variable from Twig to JavaScript

I'm using this script to have this chart 1 .

<script>

$(function () {
$('#container1').highcharts({
    chart: {
        type: 'column',
        options3d: {
            enabled: true,
            alpha: 10,
            beta: 25,
            depth: 70
        }
    },
    title: {
        text: 'Nombre De Demande Par Categorie'
    },
    subtitle: {

    },
    plotOptions: {
        column: {
            depth: 25
        }
    },
    xAxis: {
        categories: ['Education','Beauté Et Santé','Livraison','Maison Et               Jardin','Mission Et Affaire','Evénement Et Restauration','Travaux Informatique'] 
    },
    yAxis: {
        title: {
            text: null
        }
    },
    series: [{
        name: 'Demandes',
        data: [1,5,7,0,null,1,2]
    }]
});
});
</script>

But the line "data" must have variable from my data base:

series: [{
        name: 'Demandes',
        data: [1,5,7,0,null,1,2]
    }]

so i created a new function in my repository:

class DemandeRepository extends \Doctrine\ORM\EntityRepository
{
public function getNb($categorie_id)
{
    $query = $this->createQueryBuilder('u');
    $query->SELECT ('COUNT(u)');
    $query->join('u.service','s');
    $query->where('s.Categorie = :id');
    $query->setParameter('id',$categorie_id);

    return $query->getQuery()->getSingleScalarResult();

}

}

then in the controller i included the function:

class DashbroadController extends Controller
{
public function dashbroadAction()
{   
    $em = $this->getDoctrine()->getManager();

    $Categorie = $em->getRepository("tutoBackofficeBundle:Categorie")->findAll();
    $nb=array();
    foreach ($Categorie as $categorie){
        $nb[]=array(
            'categorie'=>$categorie,
            'count'=>$em->getRepository("tutoBackofficeBundle:Demande")->getNb($categorie)
            );
    }

    return $this->render('tutoBackofficeBundle:Dashbroad:dashbroad.html.twig',array('nb'=>$nb));
}
}

And in the twig :

{% for n in nb %}
{{ n.categorie }}  -> {{ n.count }}<br>

Now I want to have something like that:

data: [{{ n.count }}]

But I don't know how to pass my variable from Twig to Java Script .

Upvotes: 1

Views: 946

Answers (1)

Alain
Alain

Reputation: 36954

As far as I understand, data contains the list of count without any label.

So I guess this will do the job:

series: [{
    name: 'Demandes',
    data: [{% for n in nb %}{% if not loop.first %},{% endif %}{{ n.count }}{% endfor %}]
}]

Upvotes: 1

Related Questions