I'm working on a site where the site background is chosen randomly from among the entries in an "artwork" channel. I'm using the following code in my _layout.html
template to get the url for the chosen image:
{# choose a random entry for the site background #}
{% set randomArtwork = craft.entries.section('artwork').order('RAND()').first() %}
{# set the url for the background image #}
{% set backgroundImageUrl = randomArtwork.artImageBkg.first().url %}
The chosen image is then displayed by adding an inline style to the body tag like this:
<body{% if backgroundImage is defined %} style="background-image: url({{ backgroundImageUrl }});"{% endif %}>
Right now, this code runs on every page request and a different image is displayed on every page load on the site.
However, I'd like to be able to run this code only once per user, per site visit so that the background image will change on repeat visits to the site, but on a single visit, the user will see one persistent image.
How can I go about doing this in Craft?
As an alternative, I also thought to use Craft's {% cache %}
tags to set my template variables on a timed basis so that visitors in a particular hour would only see one persistent image, but I couldn't figure out how to get this to work.
When I tried to use the {% cache %}
tags on individual templates, I got a warning that a template that extends another (in this case, my _layout.html
template) can't have a body.
And adding the {% cache %}
tags to my _layout.html
template wasn't affecting the persistence of the background image.
Any ideas?