Forums / Developer / Selecting a random image on a page.

Selecting a random image on a page.

Author Message

Glenn MacGregor

Thursday 13 November 2003 9:38:30 am

Hi All,

I have seen some info about this doing a search but it seems to be related to ezpublish 2.2.X I have 3.2. What is the best way to select a random image tp place on the page?

Thanks

Glenn

Georg Franz

Thursday 13 November 2003 11:34:10 am

Hi Glenn,

I use a long winded solution because I don't want to touch the kernel. (The easiest solution is a "random sort" parameter in the fetch-template function, I mentioned this some weeks ago in a post, but nobody answered ...).

My solution:

You (hopefully) know in which folder your images are placed. Now you need a random number. To get the random number, you have to create an own template operator (look at http://ez.no/developer/ez_publish_3/documentation/development/kernel/custom_template_operators) for further details.

Define an operator like "random_number"

in the modify-method of your own template operator class do something like:

function modify( &$tpl, &$operatorName, &$operatorParameters, &$rootNamespace, &$currentNamespace, &$operatorValue, &$namedParameters )
{
switch ( $operatorName )
{
case "random_number":
{
$operatorValue = rand($namedParameters['start'],$namedParameters['end']-1 );
}
break;
}
}

(...)

in you .tpl do something like:

{let image_folder_id=422
image_list_count=fetch( content, list_count, hash( parent_node_id, $image_folder_id ) )
random_image=0
}

{set random_image=$image_list_count|random_number(0,$image_list_count)}
{section loop=fetch(content,list,hash(parent_node_id,$image_folder_id,
class_filter_type, "include",
class_filter_array, array(5),
offset, $random_image,
limit, 1
)) }

.... image output ....

{/section}
{/let}

Hope that helps.

Bye,
Emil.

Best wishes,
Georg.

--
http://www.schicksal.com Horoskop website which uses eZ Publish since 2004

Glenn MacGregor

Thursday 13 November 2003 12:22:35 pm

Emil,

Thanks for the input. I have done that now I have another question. What attribute of the resulting fetch do I use as the <img src to actually get the image to display?

Nicklas Lundgren

Thursday 13 November 2003 1:36:33 pm

Hi,
Another way would be to make a template operator that shuffles the items in an array randomly.
After installing such an operator it would be easy:

Fetch the images and run the operator on the resulting array. Thus the items in the array would change places randomly.

After that, you would only need to show the first item in the array.

Sincerely,
/Nicklas Lundgren, Sweden