Search code examples
phpcsssymfonyassetic

Tenant-specific CSS file in Twig master template


We have a symfony 2.4 app that is a multi-tenant one. That means we share the same codebase between a few organizations, separating the access by domain name. So it looks like:

  • organization1.domain.com
  • organization2.domain.com
  • organization3.domain.com

We also use Assetic bundle to process our .scss and .css files that are common (as of today) for all organizations. So basically all the tenants have the same design. The master layout looks like:

{% stylesheets filter='cssrewrite'
    '@MainBundle/Resources/public/css/bootstrap-2.3.1.css'
    '@MainBundle/Resources/public/css/bootstrap-responsive-2.3.1.css'
    '@MainBundle/Resources/public/sass/main.scss'
%}

where in main.scss we define all our SCSS rules for all organizations.

Now one of the organizations asks for a design change that probably the others don't want to have. I would like to place the organization-specific .css'es or .scss'es into a folder and add another stylesheets loop in my master layout. The problem is in the assetic not willing to respect the Twig variables when processing the resources. Let me explain by an example and a related question , if I do something similar to:

{% stylesheets filter='cssrewrite'
'@MainBundle/Resources/public/sass_organizations/*.css'
%}
    <link href="{{ asset_url }}" type="text/css" rel="stylesheet" media="screen, print" />
{% endstylesheets %}

after the main stylesheets loop I mentioned above, it will process ALL the resources in Resources/public/sass_organizations no matter what organization they correspond to. So I need a kind of condition in the Twig template basing on the current domain name. In other words, something like

{% stylesheets filter='cssrewrite'
'@MainBundle/Resources/public/sass_organizations/' ~ organization.id  ~ '.css'
%}
    <link href="{{ asset_url }}" type="text/css" rel="stylesheet" media="screen, print" />
{% endstylesheets %}

and if I do something like latter, assetic bundle will crash with Unexpected token \"operator\" of value \"~\" in ... exception - yes, as it doesn't know anything about Twig and its engine when processing the resources.

TL;DR: need to serve css files through assetic bundle, but not all in a folder, but basing on a condition in a Twig template.


Solution

  • In my project I use some kind like this solution: https://developer.happyr.com/rename-dump-from-asseticbundle

    We add git_commit part to output css/js name, because Amazon S3 ignores "cache busters" like filename.css?cachebuster=jhjgfsjdfg

    Instead of git_commit You can pass there whatever You want since You have access to container :)