2

Is it possible to get object from twig array knowing that the index is a javascript variable

Mycontroller

public function showContactModalAction($iduser, $profil) {
    $em = $this->getDoctrine()->getEntityManager();
    $contacts = $em->getRepository("LeymaxContactBundle:User")->findBy(array('accesslevel' => 'arch'));

    return $this->render('LeymaxContactBundle:Default:contactModal.html.twig', array('contacts' => $contacts));
}

MyTwig

 $(".fils_zone_livre").on('click', function() {
        var index=3;
        var contacts = '{{contacts[index]}}';

    });

and I tried also:

var contactArray = '{{contacts|json_encode}}';

but i get this reponse:

[{},{},{},{},{},{}]

as an empty array

1
  • 1
    It seems you are looking for an entity serializer instead of json_encode. What about jms/serializer? Commented Dec 6, 2013 at 15:10

3 Answers 3

1

You can use JMSSerializerBundle to serialize your entities instead of json_encode.

var contactsArray = JSON.parse("{{ contacts|serialize('json') }}");
var contact = contactsArray[index];
Sign up to request clarification or add additional context in comments.

Comments

1

Just needed almost the same as you.

But instead of

var contactArray = '{{contacts|json_encode}}';

you should use

var contactArray = '{{contacts|json_encode|raw}}';

Hope this helps.

Hennes

Comments

0
$(".fils_zone_livre").on('click', function() {
    var index=3;
    var contactsArray = {{ contacts|e('js') }};
    var contacts = contactsArray[index];
});

This should work. Twig parses the template on the server, before the javascript is executed, so it can't know about js variables.

2 Comments

thank you for your answer , i try it but i get this error Twig_Error_Runtime: An exception has been thrown during the rendering of a template ("Notice: Array to string conversion in C:\wamp\www\LeymaxWeb\app\cache\dev\twig\f9\f1\dcbafef3211e582ab150327ba1c59cbf3008c51290dd41d694c2b2ec9717.php line 245") in LeymaxContactBundle:Default:contactModal.html.twig at line 179.
The contacts var should be JSON encoded. You can use json_encode

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.