History always repeats itself and sometimes that's good. Here's a second chance to be part of it: tmdtc.com

Thursday, 6 March 2008

Random image in Ez Publish

I'm working further with Ez, and it's an impressive tool. There's a lot to learn and discover, but it is a really powerful system. Here's how you can have a randomly chosen image displayed in your page:

{def $nodes=fetch( 'content', 'tree',hash( 'parent_node_id', 68 ,'class_filter_type','include', 'class_filter_array', array('image')))}
{def $number_of_images = count($nodes)}
{def $to_display = rand(0,$number_of_images|dec)}
{def $image = $nodes[$to_display]}
{attribute_view_gui attribute=$image.data_map.image}

Some lines and assignments might be superfluous, but were helpful when learning how to put that together. With this code in your template, one of the images stored as a child of the node with id 68 will be displayed.

One gotcha is that arithmetic operations don't work in the .tpl files, hence the use on |dec to decrement the variable $number_of_images.

Also, be sure to put this outside of all cache-block, or your image will be chosen once and for all the first time the template is compiled as it would be cached from then on!

And notice the call to attribute_view_gui to render the image.

You can do this with any other type of nodes, for example for the latest news, or customer quotes. I already see a use for the future Profoss website :-)


metamatik said...

Well, okay, except that if you have 10000 images you're going to fetch them all and probably kill your DB server in the process :)

It really, really depends on content volume.

Bottomline: a fetch, such as this one, without an explicit limit parameter, can be a complete performance killer. Beware.

PS: just found this entry while googling about eZ performance. Felt compelled to comment. Don't mind me ;)

RedQueen said...

Just bumped into this thread, though it's old. You should first get image count, then define your random number using it, then you should fetch only one image - a fetch with limit 1 and offset equal to your random number. Otherwise your page will be slow beyond any reasonable load time.