我可以动态更改 SilverStripe 主题吗?

Can I dynamically change SilverStripe theme?

我为 cecutients(视力不好的人)制作了额外的主题。我可以按主页上的某个按钮动态更改网站主题吗?

是的,你可以做到。我建议您在控制器上执行一个操作来更新主题。然后,您可以将当前活动的主题存储在会话中,并在访问页面时使用它。

以下是我的实现方式(在您的 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();
    }
}

现在您的 Page_Controller 中有一个 changeTheme 操作,这意味着您可以在每个页面上使用它。然后你可以简单地用 link 触发主题更改,例如:

<%-- replace otherTheme with the folder-name of your theme --%>
<a href="$Link('changeTheme')/otherTheme">Change to other theme</a>

在您的基本主题的 Page.ss 模板中,您可以为 cecutients 添加一个 link 到主题。在 cecutients 的主题中,您将 link 添加到基本主题。

Silverstripe 4.x 版本更新:

use SilverStripe\CMS\Controllers\ContentController;
use SilverStripe\Control\Session;
use SilverStripe\SiteConfig\SiteConfig;
use SilverStripe\View\SSViewer;
use SilverStripe\Core\Config\Config;

class PageController extends ContentController
{

    private static $allowed_actions = ['changeTheme'];

    protected function init()
    {
        parent::init();
        if ($theme = $this->getRequest()->getSession()->get('theme')) {
            SSViewer::config()->update('theme_enabled', true);
            SSViewer::set_themes([$theme]);
        }            

    }

    public function changeTheme()
    {
        $theme = $this->request->param('ID');
        $existingThemes = Config::inst()->get('SilverStripe\View\SSViewer', 'themes');
        if (in_array($theme, $existingThemes)) {
            SSViewer::config()->update('theme_enabled', true);
            SSViewer::set_themes([$theme]);
            $this->getRequest()->getSession()->set('theme', $theme);
        }

        return $this->redirectBack();
    }        
}