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?

1 Answer 1


Sounds like you need a good cookie solution to keep track of which background has been chosen for each visitor.

I'd recommend using the LJ Cookies plugin to easily set & retrieve the filename of the background image.

(I don't believe the cache tag will be useful to you in this case.)

  • Thanks for the recommendation Lindsey. I was hoping there would be a native way to accomplish this without having to resort to a plug-in. Commented Jan 6, 2015 at 20:23
  • The closest thing to a native way of handling this would be to write a small plugin with a template hook, and let your template hook get & set the cookie for you. But honestly, that's practically the same thing, so I'd still recommend going with the lightweight LJ Cookies plugin.
    – Lindsey D
    Commented Jan 6, 2015 at 21:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.