Snippets - Little bits of code to make you happy
Select a theme using a URL parameter
Tweet21 December 2009 | |
When I develop SilverStripe sites, I usually get functionality working in the default theme blackcandy before getting it working in the final templates. This way, authors can start adding content and seeing how it looks on the page, and I can get early feedback about the functionality. Also, as a developer I get to see real content in the browser early in the process. So does the designer.
I'm sure this process is nothing new - and I realise form-first vs function-first is an old debate - but one thing I wanted to share is some code my team and the client found useful in a recent project.
I added the ability to select a theme based on a parameter in the URL, either for the current page request or for session. This meant we were able to throw around URLs specifying the theme, choosing a theme depending on whether we were discussing the (visual) design or the functionality and content.
http://www.mywebsite.com/myurlsegment/?theme=blackcandy
sets the theme for a single request.
http://www.mywebsite.com/myurlsegment/?setTheme=blackcandy
sets the theme for the session.
Early in the client project, I made sure all the functionality and content worked in both themes, but as more pages worked in the real theme, we left blackcandy behind.
Having said that, I kept the most involved pages working in blackcandy right until the end, so we could always view the new content, such as a large image due to be displayed in a lightbox, or content due to be included in a slider effect was implemented. That way, we kept the feedback coming: by the time the lightbox effect worked, we already knew the image was getting all the way from author to browser, appropriately downsampled and compressed, and everyone was already happy with the size and quality of the large image.
Here's the essence of code, suitably unrefactored for your viewing pleasure.
class Page_Controller extends ContentController {
function init() {
parent::init();
if (isset($_GET['setTheme'])) {
if (Director::isDev() || Permission::check('ADMIN')) {
Session::set('theme', $_GET['setTheme']);
} else {
Security::permissionFailure(null,
'Please log in as an administrator to switch theme.');
}
}
if (isset($_GET['theme'])) {
if (Director::isDev() || Permission::check('ADMIN')) {
SSViewer::set_theme($_GET['theme']);
} else {
Security::permissionFailure(null,
'Please log in as an administrator to set the theme.');
}
} elseif (Session::get('theme')) {
SSViewer::set_theme(Session::get('theme'));
}
}
See also Martijn van Nieuwenhoven's SSbits snippet: Create a front end theme switcher
1 Comments
RSS feed for comments on this page RSS feed for all comments
Johannes Fischer
19/09/2011 2:38pm (5 months ago)
Is there a more elegant and secure way to get a get-parameter?
Post a comment ...
You cannot post comments until you have logged in. Login Here.