Include Bootstrap in Symfony 2 application


{% comment %}

The best tool to design nice, responsive, mobile first web applications is bootstrap framework. It is  also integrated as form design theme in symfony.

Before you can use it in your symfony application, you will need to install it.

The easiest way is with a web front-end package manager - bower. You should install node first and then install bower with npm package manager.  Then including resources in your twig templates is as easy as use asset component.

Isn’t this little to much to start with ?


If you don’t know what node/npm/bower is or if you don’t want to know (for now) :-) , you can just use bootstrap directly from publicly accessible  CDN links. Do not forget to include jquery library first, it is required by bootstrap.

Just don’t forget, if you take shortcuts, you get cut short.

Using bower

Why we needs front-end package management ?  With front-end package manager we simplify installing and updating project dependencies for client side libraries. Bower also check inter-dependencies between those libraries and won’t install the package incompatible with one that’s already installed.

If you use bower for front-end package management  and don’t want to use default download directory (“bower_components”), just create local config file “.bowerrc”:

{ “directory”: “libs” }

Then you can install bootstrap with a command :

H:\Ampps\www\webapp05\www\> bower install –save bootstrap

You will get two sub folders, “bootstrap” and “jquery”, inside “libs” folder.

Asset component

With asset component we generate URL addresses of web assets such as CSS, stylesheets, graphics and Javascript files. This means that you can change location of assets at one place  in configuration file.

We create new  “assets” section in “framework”  section of config.yml file and add three “packages” inside :

framework: assets: packages: jquery: base_path: /libs/jquery/dist/ bootstrapjs: base_path: /libs/bootstrap/dist/js/ bootstrapcss: base_path: /libs/bootstrap/dist/css/

With that in place we can define URL location in our template file with asset function, for example:

Second parameter in asset function is package location from config.yml file.

And the final twig file with all required includes for bootstrap is :

{% endcomment %}