Can I dynamically change the SilverStripe theme?
1 answer
Yes, you can do it. I suggest that you take an action on your controller that will update the theme. Then you can keep the current active theme in the session and use it whenever the page is visited.
This is how I would implement it (in Page_Controller
):
class Page_Controller extends ContentController
{
private static $allowed_actions = ['changeTheme'];
public function init(){
parent::init();
if ($theme = Session::get('theme')) {
Config::inst()->update('SSViewer', 'theme', $theme);
}
}
public function changeTheme()
{
$theme = $this->request->param('ID');
$existingThemes = SiteConfig::current_site_config()->getAvailableThemes();
if (in_array($theme, $existingThemes)) {
// Set the theme in the config
Config::inst()->update('SSViewer', 'theme', $theme);
// Persist the theme to the session
Session::set('theme', $theme);
}
// redirect back to where we came from
return $this->redirectBack();
}
}
Now that you have an changeTheme
action in Page_Controller
, this means you can use it on every page. Then you can simply trigger the theme change with a link like:
<%-- replace otherTheme with the folder-name of your theme --%>
<a href="$Link('changeTheme')/otherTheme">Change to other theme</a>
In Page.ss
your base theme template, you can add a theme link for cecutients. And in the topic for cecutients you add a link to the base topic.
+4
source to share