SS4: Replacement for good ol’ $ThemeDir: or loading themed resources

The upgrade to SS4.1 has changed how themed resources (and any other resources) need to be loaded. They will need to be loaded from the public/resources/ directory now. The theme dir is no longer in the webroot but one level above and therefore not accessible through the browser. The same is for all modules; these reside inside vendor/ and are outside the webroot.

How can we access e.g. an image or css that are in my theme? These assets will need to be exposed, by adding these lines to our project’s composer.json:

Example:

    "type": "silverstripe-project",

    "extra": {
        "expose": [
          "themes/<theme-name>/src",
          "themes/<theme-name>/dist",
          "themes/<theme-name>/images",
          "themes/<theme-name>/fonts"
        ]
    },

This is an example from my composer file. When it gets installed, those directories will now be accessible in public/resources/themes/<theme-name>.

Please note, that you need to add “type”: “silverstripe-project” (or anything starting with “silverstripe-”) to get your files exposed. Otherwise it’s simply ignored.

When you run

composer vendor-expose

in your CLI, all files and directories you defined are symlinked or copied to the resources directory and are now accessible through the webserver.

Including resources in the templates

These assets need to be called a little different in the template files now. If you are writing a theme that will be used in both SS4.0 and SS4.1 (or if you don’t use /public/ webroot for some reason), no worries - it’s a universal requirement declaration.

CSS example:
<% require css($resourceURL('themes/<theme-name>/dist/css/app.css')) %>

JS Example:
<% require javascript($resourceURL('themes/<theme-name>/dist/javascript/scripts.min.js')) %>

When using the $resourceURL(), SilverStripe is smart enough to know whether it needs to pull from the public/resources directory or if it can pull things right from the theme directory.

If you have cascaded themes enabled, $resourceURL() will go through all themes and return the first match. This way you can easily overwrite a stylesheet in a subtheme and other resources are picked from the main theme.

Rate this post (5 rating(s))

Post your comment

Comments

No one has commented on this page yet.

RSS feed for comments on this page | RSS feed for all comments