Question

I'm building a single page app with AngularJS on front-end and Symfony 2 on the backend. I would like to make the app modular and keep Angular modules in sync with Symfony bundles.

For example, if I have Articles module in angular angular.module('Articles', []), I probably would like to keep all Articles assets (js files for services, controllers & directives, CSS files, html partials) in MyNamespace\ArticlesBundle Resources folder.

Let's say I can use some features in AngularJS at run-time if corresponding Symfony bundles are registered in the kernel (let's ignore the fact there might be js errors for unresolved dependencies if some module depends on bundle that is not registered).

Is there a way to configure assetic from MyNamespace\ArticlesBundle so that it would add all required assets into main layout for this bundle if it is registered? Like having separate assets.yml in config for every bundle:

//MyNamespace/ArticlesBundle/Resources/config/assets.yml
assetic:
  assets:
    js:
      input:
        - '@ArticlesBundle/Resources/public/js/controllers.js'
        - '@ArticlesBundle/Resources/public/js/directives.js'
    css:
      input:
        - '@ArticlesBundle/Resources/public/css/main.css'

and merging it with app/config/config.yml assetic section? And then in layout it should output assets of all registered bundles:

{% javascripts '@js' %}
<script type="text/javascript" src="{{ asset_url }}"></script>
{% endjavascripts %}
Was it helpful?

Solution

I think your need is covered by this bundle:

https://github.com/AppVentus/AsseticInjectorBundle

In each bundles you create, you can add a "Resources/config/assetic_injector.json" file, that define which asset to inject, and under which tag:

//ArticleBundle/Resources/config/assetic_injector.json
{
    "require_all":
    {
        "javascripts":
        {
            "angular":
            [
                "@ArticlesBundle/Resources/public/js/controllers.js",
                "@ArticlesBundle/Resources/public/js/directives.js"
            ]
        },
        "stylesheets":
        {
            "angular": "@ArticlesBundle/Resources/public/css/main.css"
        }
    }
}

You just have to add the filter "injector" on your "{% javascripts %}" and "{% javascripts %}" blocks and it's done.

{% javascripts injector="angular" %}
<script type="text/javascript" src="{{ asset_url }}"></script>
{% endjavascripts %}


{% stylesheets injector="angular" %}
<script type="text/javascript" src="{{ asset_url }}"></script>
{% stylesheets %}

If you have other bundles with angular assets dependency, you can easily create an assetic_injector.json file for them, and all assets under the "angular" tag will be automatically injected.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top