Andy Holmes
Andy Holmes

Reputation: 8047

How can i pull data from my symfony2 controller into my chart in show.html.twig?

I have this code in my controller:

public function showAction($name)
{
    $weights = "3,5,8,12,16,21";

    $em = $this->getDoctrine()->getManager();

    $entity = $em->getRepository('BreedrGeckoBundle:Gecko')->findOneByName($name);

    if (!$entity) {
        throw $this->createNotFoundException('Unable to find Gecko entity.');
    }

    $deleteForm = $this->createDeleteForm($name);

    return array(
        'entity'      => $entity,
        'weights'     => $weights,
        'delete_form' => $deleteForm->createView(),
    );
}

As you can see i have some data inside $weights which i would like to move into my show.html.twig file. Inside this file i am using {{dump(weights)}} which dumps that data fine. How can i use this data inside some jQuery as data points on my chart? I essentially need to transfer it into a javascript variable.

Upvotes: 0

Views: 48

Answers (1)

Nickolaus
Nickolaus

Reputation: 4835

Currently you are just tranferring a string of numbers to the template...
if you want to use the variable in javascript you simply need to set the content of the twig-var to the js-var:

var myJsVar = {{ myTwigVar|default('') }}

this sets your js-var to the twig var or to an empty string if the variable can't be found or is empty...

PS: I don't know what you want to accomplish but I think an array of values would be more appropriate.

Upvotes: 1

Related Questions