Profile pic of Tommy KuTommy Ku's Blog

Reading and thinking

Resolve syntax conflict between AngularJS and Twig

Posted on  by Tommy Ku

This post is more than 2 years old, it may contain outdated information

AngularJS uses double curly braces (e.g. {{var}}) to wrap the variables in its HTML view while Twig use precisely the same syntax to wrap the variables. Should you use Twig to render a AngularJS app, the HTML view template will simply be messed up.

There are two solutions suggested by the online community:

  1. Convert all double curly braces into literal strings

    As suggested by the official documentation of Twig, when rendering literal {{ }} one can ‘escape’ it like the following.

    {{ -> {{ '{{' }} or {{var}} -> {{ '{{var}}' }}

    No doubt the AngularJS template will look terrible, but this solution resolves the conflict without tweaking the options of both AngularJS and Twig.

  2. Configure AngularJS to use other braces such as {[{var}]} (or whatever you like) instead.

    In your AngularJS app script, add the following config.

    angular.module('app', []).config(function($interpolateProvider){
      $interpolateProvider.startSymbol('{[{').endSymbol('}]}');
    });
    

    This method breaks less of the syntax in both Twig and AngularJS, so it is strongly suggested.

  3. Twig also provide a tag for displaying raw content. Everything inside vertatim block is not parsed by Twig engine.

    {% verbatim %}
    // everything of your angularJS template
    {% endverbatim %}
    

    This one should be the least obstructive and the easiest to implement.

edited 2014-07-26

You could also look at...

This post first appeared on . Permalink:

About the author

Profile pic of Tommy Ku

Tommy Ku, a Hong Kong-based Software Engineer experienced developing PHP and Java-based web solutions and passionate in Web technology.

Also a hobbyist digital and film photographer.