Themes

Themes in CakePHP are simply plugins that focus on providing template files.See the section on Creating Your Own Plugins.You can take advantage of themes, making it easy to switch the look and feel ofyour page quickly. In addition to template files, they can also provide helpersand cells if your theming requires that. When using cells and helpers from yourtheme, you will need to continue using the plugin syntax.

To use themes, set the theme name in your controller’s action orbeforeRender() callback:

  1. class ExamplesController extends AppController
  2. {
  3. public function beforeRender(\Cake\Event\EventInterface $event)
  4. {
  5. $this->viewBuilder()->setTheme('Modern');
  6. }
  7. }

Theme template files need to be within a plugin with the same name. For example,the above theme would be found in plugins/Modern/templates.It’s important to remember that CakePHP expects PascalCase plugin/theme names. Beyondthat, the folder structure within the plugins/Modern/templates folder isexactly the same as templates/.

For example, the view file for an edit action of a Posts controller would resideat plugins/Modern/templates/Posts/edit.php. Layout files would reside inplugins/Modern/templates/Layout/. You can provide customized templatesfor plugins with a theme as well. If you had a plugin named ‘Cms’, thatcontained a TagsController, the Modern theme could provideplugins/Modern/templates/Plugin/Cms/Tags/edit.php to replace the edittemplate in the plugin.

If a view file can’t be found in the theme, CakePHP will try to locate the viewfile in the templates/ folder. This way, you can create master template filesand simply override them on a case-by-case basis within your theme folder.

If your theme also acts as a plugin, don’t forget to ensure it is loaded inyour application’s bootstrap method. For example:

  1. // Load our plugin theme residing in the folder /plugins/Modern
  2. $this->addPlugin('Modern');

Theme Assets

Because themes are standard CakePHP plugins, they can include any necessaryassets in their webroot directory. This allows for easy packaging anddistribution of themes. Whilst in development, requests for theme assets will behandled by Cake\Routing\Dispatcher. To improve performance for productionenvironments, it’s recommended that you Improve Your Application’s Performance.

All of CakePHP’s built-in helpers are aware of themes and will create thecorrect paths automatically. Like template files, if a file isn’t in the themefolder, it will default to the main webroot folder:

  1. // When in a theme with the name of 'purple_cupcake'
  2. $this->Html->css('main.css');
  3.  
  4. // creates a path like
  5. /purple_cupcake/css/main.css
  6.  
  7. // and links to
  8. plugins/PurpleCupcake/webroot/css/main.css