Preview Your Theme Styles

I was working on creating a preview window in the theme settings page for a theme I was implementing. See Garlands preview for an idea of what I’m talking about. It was a simple idea that the user would choose the style they wanted of that theme and it would update an image on that page that would show the preview of that style.

Here is how I accomplished it. Getting the paths to the theme I am configuring was hard to find. I am using a hacky solution that probably could be done better. Please tell me if you know how to do it better.

First, here is the layout of my theme folder.

theme-
|- css
| |- color
| | |- black.css
| | |- blue.css
| |
| |- style.css
|
|- images
| |- black
| | |- header.png
| | |- screenshot.png
| |
| |- blue
| | |- header.png
| | |- screenshot.png
|
|- js
|- page.tpl.php
|- template.php
|- theme.info
|- theme-settings.php
|- screenshot.png

The screenshot.png that is in the image folder will be the one that will show on the preview window. Create a theme-settings.php file and put this code in it.

<?php
function phptemplate_settings($saved_settings) {

//Set the default style
$defaults = array(
'my_theme_style' => 'gray',
);

$settings = array_merge($defaults, $saved_settings);

//Here is the hacky code.  It get's all the theme's info.
$themes = list_themes();

//Then grabs the information for just our theme.
$theme_object = $themes['my_theme'];

//We specifically grab the .info file, remove the my_theme.info from the end and
//then we add base_path to the beginning to give us the theme path.
$theme_path = base_path() . rtrim($theme_object->filename,'my_theme.info');

//Create a form item that just prints out our javascript code.  This code updates
//the image when the select box is changed.
$form['my_theme_js'] = array(
'#value' =>'<script type="text/javascript">
 function updatePreview(style){ document.getElementById("my_theme_preview").src="'. $theme_path .'images/" + style + "/screenshot.png";}</script>',
);

//Create our select box with an onChange attribute that runs our js code.
$form['my_theme_style'] = array(
'#type' => 'select',
'#title' => t('Style'),
'#default_value' => $settings['my_theme_style'],
'#options' => array(
'black' => t('Black'),
'blue' => t('Blue'),
),
'#attributes' => array('onChange' => 'updatePreview(this.value)'),
);

//This creates a form item for our preview.  It prints out the img tag along with our
//current theme image.
$form['my_theme_preview'] = array(
'#type' => 'item',
'#title' => t('Preview'),
'#value' => '<img style="border:1px solid #999;" src="'. $theme_path .'images/'. $settings['my_theme_style'] .'/screenshot.png" alt="" />',
);

return $form;

}

Now that we have that created we are ready to test the preview function. As long as you have built your theme with the layout that I have you should be able to change styles and the preview should update.

Explore posts in the same categories: Drupal, PHP, Templates

Comment: