Angularjs on a symfony2 application

SymfonyAngularjs

Symfony Problem Overview


I'm working on a SF2 application that uses a lot of javascript on the front end.

SF2 provides me a good way of building a nice REST app, manage my database with doctrine, use twig for templates and so on, but I would like to use Angularjs.

I know that angularjs an SF2 are 2 different framework with different approach, but I'm wondering what the best way to make this work is.

Is it even worth it?

If yes, what do you think is the cleaner and most efficient solution?

Maybe use php instead of twig for templates to use angularjs curly braces ?

Symfony Solutions


Solution 1 - Symfony

I think Symfony2 can perfectly work well with AngularJS. Proof is I'm making an API on one side using Symfony, and a web app on the other side with AnglularJS.

Moreover, for some reasons I generate my views in my web app with Twig. I simply embed angular's curly braces in a twig {% verbatim %} {% endverbatim %} statement each time I need to use Angular in my views.

Solution 2 - Symfony

As of Twig 1.12 the raw tag was renamed to verbatim:

{% verbatim %}
    <ul>
    {% for item in seq %}
        <li>{{ item }}</li>
    {% endfor %}
    </ul>
{% endverbatim %}

Everything in-between won't be parsed by the Twig Engine and can be used by AngularJS.

Though I'd recommend changing the AngularJS delimiters. Otherwise it can be hard to distinguish between Twig and AngularJS code when looking at your templates.

Solution 3 - Symfony

I face the same situation, in my case, I've decided to split the client and server projects, I used symfony2 as server-side because it's simplicity and usability besides other advantages that brings to me. By other hand I created a simple HTML project with AngularJS, that is useful for me because I want to create a HTML5 Mobile App with the same client files.

In that case, I think that the core of the problem here is in the authentication and authorization process. You must implement a secure firewall for working in REST (for example WSSE: Symfony2: How to create a custom Authentication Provider) in the server side.

And then the corresponding implementation in the client side (AngularJS), the most useful resource that i found: Github:witoldsz/angular-http-auth.

If you want deeper implementation with your sf2 project, you can compile AngularJS using Assetic's filters, and gain performance in page loading.

Solution 4 - Symfony

I have used the following code to change the AngularJS delmiters

Coffeescript:

# Change the angular delimiters for twig compatability
# and load module with ngResource
WAFapp2 = angular.module("WAFapp2", ['ngResource'], ($interpolateProvider) ->
  $interpolateProvider.startSymbol "{[{"
  $interpolateProvider.endSymbol "}]}"
)    var WAFapp2;

or Javascript:

var WAFapp2;

WAFapp2 = angular.module("WAFapp2", ['ngResource'], function($interpolateProvider) {
  $interpolateProvider.startSymbol("{[{");
  return $interpolateProvider.endSymbol("}]}");
});

then at the top of my layouts:

<!DOCTYPE html>
<html lang="en" data-ng-app="WAFapp2">
  <head>

then later in the body tag section of the html I can use:

<ul>
{% for item in seq %}
    <li>{[{ item }]}</li>
{% endfor %}
</ul>

I think this keeps things cleaner, and allow easy mixing of twig and angular tags. This seems to work well for me.

Solution 5 - Symfony

A good solution for the two mustaches to avoid the confusion is the attribute-based directive called ng-bind: <p ng-bind="yourText"></p> is the same as <p>{{yourText}}</p>

Solution 6 - Symfony

Keeping the angular app separate is more advisable. Just use Symfony as an api for data retrieval/persistence and as security provider.

This would allow greater separation of view and the data layer. As a result you can start working on the frontend side without thinking yet of the backend implementation. You just need to mock the api calls.

Solution 7 - Symfony

I've been trying to build a single page application using Symfony and angularjs. I used Symfony2 with the FOSRestBundle to build an Restful API and Angularjs to build the frontend.

By itself, AngularJs does not need Symfony2 framework to build a application as long as it has an API to talk with. However, I found Symfony2 useful in these area:

  1. Translation in the template. the data in the API payload does not need translation in most cases. Using Symfony I18N support for the template makes perfect sense.

  2. Loading of Option lists. Say you have a country list with 200+ options. You can build an API to populate a dynamic dropdown in angularjs, but as these options are static, you can simply build that list in twig.

  3. Preloading data/content. You can preload template or JSON data in the hosting page if you like

  4. Take advantage of the authentication feature of Symfony. You can used the same authenticated session to the API for the application, too. No need to use Oauth.

  5. The Assetic bundle is very useful to urglyfy and minify bunches of Javascript files used by AngularJs

However, I did find the following challenges:

  1. PHP session locking for multiple Ajax calls. Need a better way to free the php session by calling 'session_write_close()' or use a database for session. Where is the best place in Symfony to call that 'session_write_close' function so that we can free the session for more ajax calls as soon as possible ?

  2. Reloading/Syncing loaded data Say you have a list of items (like ebay items) showing in a browser, you want to update that list in client's browser when the list was updated on the server side. You might need to poll the list periodically or use something like Firebase. Firebase is an overkill in most cases, polling is not nice looking to me, but what is the best way to achieve this ?

Please add you comments. thanks

Solution 8 - Symfony

You can use this template or you can study this template and you can based in it.

Is a template application with secured communication via a RestFul API between the client part with AngularJS and the server part with Symfony2.

Another project that you should check is Aisel is open-source CMS for highload projects based on Symfony2 and AngularJS

Solution 9 - Symfony

I have been facing a lot of issues myself trying to make Symfony and AngularJS work together. However while working on it I learned a few things which may help you:

  1. To separate the AngularJS expressions {{ variable }} from twig curly braces you have three alternatives :

a). Use the quotes around the AngularJS expressions {{ '{{ variable }}' }}

b). Surround your AngularJS code with {% verbatim %} your code {% endverbatim %}

c). Use AngularJS interpolateProvider service

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

2. In the js file, twig can’t generate the URL for you. For this you can use "friendsofsymfony/jsrouting-bundle". After installing it you can use it as: $http.get(Routing.generate('route_name', {'id':id}));

This may not work for you for submission, why? One thing you should know about the $http.post is that it dosen’t send the data as “Form Data” but as “Request Payload”, which is the normal way to transmit data via HTTP POST. The problem is that this “normal way” is not equivalent to a form submission, which causes problem in interpreting data with the Symfony Request object.

use this instead:

$http.put(url, $.param({foo: 'bar'}), {
     headers: {'Content-Type': 'application/x-www-form-urlencoded'}
 });

3. When you want to know if a request is an AJAX request within the controller, we usually use the isXMLHttpRequest() method. The problem is that Angular don’t identify its requests as an XMLHttpRequest requests. Use this:

var app = angular.module('myModule', []); app.config(['$httpProvider', function($httpProvider) { $httpProvider.defaults.headers.common["X-Requested-With"] = 'XMLHttpRequest'; }]);

  1. While creating forms you can choose to display the form through AngularJS and let Symfony Form to handle the request. For that you need to disable the CSRF protection:

    public function setDefaultOptions(OptionsResolverInterface $resolver) { $resolver->setDefaults(array( 'data_class' => '...', 'csrf_protection' => false )); }

Now your symfony Form can receive data from a custom Angular request.

All the things aside, I am still not sure about one thing, whether to display your form using Symfony or AngularJS.

Hope this helps.

Solution 10 - Symfony

In theory, you would have only your index page being rendered from symfony, so you don't have to use twig at all. you only need to render first page and then angular framework takes over. Angularjs has its own template syntax and capabilities. I don't think there is a need to mix those two, as you can completely separate both frameworks.Perhaps, make your server respond with file index.html (your angular app) on yourdomain.com, and everything from symfony comes from /api prefix, or something like that. Just imagine your WebApi project is one server and angularjs project on the other. they would only talk through api calls, no need to mix templates at all, in my opinion.

Solution 11 - Symfony

Searching through the web, I came across different solutions. You can, for example as said before, change the angular symbols. However, I preferred to keep it the most simple as possible by simply telling twig to output the angular symbols:

{{ '{{entity.property}}' }}

http://louisracicot.com/blog/angularjs-and-symfony2/

Solution 12 - Symfony

Use {@ variable @} in templates. After template generated just replace {@ with {{ and @} with }} with simple str_replace function. This way is clean and much faster then strings concatination and so on.

Solution 13 - Symfony

I have come across the same situation where I had to develop a single page application using AngularJS on top of Symfony2.

If you can separate the two apps, perfect!!! It would create a great separation of the Model and View layer. If not, as was the case with my application, you can surely use AngularJS with Symfony2 and TWIG perfectly fine.

I used quotes around the AngularJS expressions like -

{{ '{{someAngularJsExpression}}' }}

It just takes some time to get used to it but when you do, you're not going to face many problems. Symfony also allows you to use other templating engines but I'd prefer not to.

So my advice is to either have two different applications for AngularJS and Symfony. If you don't have the resources to do so, you can do the way I did. Don't worry, you'll get used to it.

Solution 14 - Symfony

Today everyone want symfony backend with api and angular/vue frontend - it's nice but this way we're loosing all symfony ability in frontned.

I'm sucessfully using angular with my symfony apps. Maybe it's not high performance thing , but it works.

Some tips for you :

1

read about $interpolateProvider

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

This way you can change {{ }} in angular for something else. I'm using {[{ and }]} , so it wont interfere with twig

2

second best thing here is https://symfony.com/doc/master/bundles/FOSJsRoutingBundle/index.html

This connect symfony routing with js , so all your angular views / or ajax calls in js can be generated by symfony - this gives you a huge possibilities

Solution 15 - Symfony

You can simply escaped curly brackets like:

Hello {{ '{{' }} name {{ '}}' }}

and it will be parsed to the next HTML code:

Hello {{ name }}

You also can try to use left and right curly braces HTML coded character set, for example:

&#123; name &#125;

But I don't sure that it will be understand by AngularJS lib :).

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionLouis GrelletView Question on Stackoverflow
Solution 1 - SymfonyHalim QarroumView Answer on Stackoverflow
Solution 2 - SymfonyacmeView Answer on Stackoverflow
Solution 3 - SymfonyIván GuillénView Answer on Stackoverflow
Solution 4 - Symfonygcman105View Answer on Stackoverflow
Solution 5 - SymfonypabloRNView Answer on Stackoverflow
Solution 6 - SymfonykenView Answer on Stackoverflow
Solution 7 - SymfonyDavid LinView Answer on Stackoverflow
Solution 8 - SymfonyCristianView Answer on Stackoverflow
Solution 9 - Symfonyutkarsh2k2View Answer on Stackoverflow
Solution 10 - Symfonyqwerty_igorView Answer on Stackoverflow
Solution 11 - SymfonyDizzy Bryan HighView Answer on Stackoverflow
Solution 12 - SymfonyAleksandr AleksandrView Answer on Stackoverflow
Solution 13 - SymfonyRahul SharmaView Answer on Stackoverflow
Solution 14 - SymfonyMichał GView Answer on Stackoverflow
Solution 15 - SymfonyVictor BocharskyView Answer on Stackoverflow