Warning

This document hasn't been checked for compatibility with current versions of Plone. Use at your own risk.

Creating random rotating images anywhere in your Plone site

by Mike Takahashi last modified Dec 30, 2008 03:02 PM
Need to have a rotating image on your home page each time a user visits your site? By creating a simple Python script, you can achieve this by using only the <img> tag.

The first step is to create a Python script that will serve up the image you want. This assumes that you want a random image from a folder to be chosen. Python-savvy readers can use more advanced techniques, such as making a list of images to load in the same order, etc.

Through the ZMI go to /plone_skins/custom folder, and add a Script (Python) object from the drop down menu. Name this “randomimg” without the quotes and put this code into it:

from random import choice
# Import a standard function, and get the HTML request and response objects.
from Products.PythonScripts.standard import html_quote

request = container.REQUEST
RESPONSE = request.RESPONSE
RESPONSE.setHeader('Content-Type','image/jpeg')

# Get list of images in randomimages folder
images = context.randomimages.getFolderContents({'portal_type':'Image'}) 

# Return a random choice of one of the images
return choice(images).getObject().data 

 

This assumes your images will be stored in the "randomimages" folder in the root of your Plone site. Change the reference to wherever your images are being stored if need be.

If you are using images other than JPEGs, you will need to change the setHeader call so its second parameter reflects the image type you’re using. For example, image/gif or image/png.

Now that the script is in place, you can test it by pointing your browser to http://your.plone.site/randomimg. It will work just like a normal image file on a web server. To add the image anywhere in your site, add the usual image HTML tag: <img src=”/randomimg” />. This calls the Python script above and does its magic. Every time the page is reloaded, a randomly-selected image from your "randomimages" folder will be shown.


Contribute

Something wrong or out of date? Anybody can edit or create a new article in the knowledge base. Simply create an account on this site, log in, and click the Edit button to contribute.