Using AngularJS with Twig

November 24, 2015 | No Comments | Programming | angularjs PHP twig

There are so many questions on StackOverflow about integrating AngularJS with Twig . I want to share with you some tricks which will help you with this task.

Basic knowledge when you want to use AngularJS with Twig

First, you should understand the difference between front-end and back-end frameworks. Usually front-end communicates with back-end using API and Ajax. But what if you have complex application with multiple SPA’s and in this case you have to use Twig and AngularJS together. There are other cases but I guess It’s common one.

Curly Braces

Both Twig and Angular are using curly braces for variables. Twig will complain if you use curly braces for AngularJS variables. There are many ways to avoid it but in my opinion better to include AngularJS tags inside Twig tags like this:

<ul ng-repeat="phones in phone">
    <li>{{ '{{ phone.name }}' }}</li>
</ul>

This will be much simpler than tweak variables braces or use verbatim tags in twig. Also I notices that verbatim tag has some problems in my IDE PHPStorm 9 with auto indentation.

Passing variables from Twig to AngularJS

Rarely we have to pass variable directly from Twig variable to AngularJS. It can be done in multiple ways, here is the one:

{% set users = [{'name':'John Doe'},{'name':'Jane Doe'}] %}
 
<div ng-app="UsersApp">
    <div ng-controller="UsersListCtrl" ng-init='users={{ users|json_encode|raw }}'>
        <ul ng-repeat="user in users">
            <li>{{ '{{ user.name }}' }}</li>
        </ul>
    </div>
</div>

I encoded variable in json and initialized it in AngularJS by using ng-init directive.

Conclusion

Also some developers asking about project structure using AngularJS with Twig but it’s project dependent thing. I can only suggest here to read official docs about bundle assets. Even though best practice is storing assets in web/ folder I would recommend to store them in your bundle if you’re using Symfony 2. Complex app always require modular design.

Those are common problems I’ve met in my projects. Maybe in future I will share some more.


About the Author / Artem Zhuravlev

Artem Zhuravlev. Web developer. Blog writer.

Need help with your website ? Contact with me by email infzanoza@gmail.com for services of experienced web developer.

Follow @infernosquad

LEAVE A COMMENT