[TYPO3-english] display random value from array in fluid template

Xavier Perseguers xavier at typo3.org
Thu Jun 13 08:28:14 CEST 2013


Hi Muriel,

> I want to display a random image so in good old PHP it would be
> something like:
> 
> $nr = rand(0,10);
> $img[$nr];
> 
> settings.icons contains an array with images.
> 
> The ViewHelper I created works and I can output the content in the
> template like this:
> <f:render partial="Cases/Images" arguments="{images:randomnr}" />
> 
> But how do I render settings.icons.[number generated by ViewHelper]?

A complete example would help a lot.

So "settings.icons contains an array with images", I guess you mean
something like that:

settings.icons {
	1 = IMAGE
	1.file = fileadmin/whatever.jpg

	2 = IMAGE
	2.file = fileadmin/path/to/mypicture.png

	3 = IMAGE
	3.file = fileadmin/yet-another-one.jpg
}

And you'd like to choose a random one, so:

<f:render partial="Cases/Images" arguments="{RANDOM-TS-HERE}" />

Your Cases/Images (why plural form?) takes a TypoScript path and should
render it, right? So you expect a call like

<f:render partial="Cases/Images" arguments="settings.icons.2" />

to be made. And your partial is basically only doing:

<div class="pretty-picture">
	<f:cObject typoscriptObjectPath="{objectPath}" />
</div>

First is to create your VH and within your render() method, you do your
logic, count the number of entries under settings.icons and return a
full path:

class Tx_MyExt_ViewHelpers_RandomObjectPathViewHelper extends
Tx_Fluid_Core_ViewHelper_AbstractViewHelper {

	/**
	 * @param string $basePath
	 * @return string
	 */
	public function render($basePath) {
		// TODO: count items from TS $basePath
		// snip, hardcoded return value
		return 'settings.icons.2';
	}
}

Then modify your "<f:render partial" to use your VH:

{namespace my=Tx_MyExt_ViewHelpers}
<f:render partial="Cases/Images"
arguments="{my:randomObjectPath(basePath:'settings.icons')}" />

HTH

-- 
Xavier Perseguers
Release Manager TYPO3 4.6

TYPO3 .... inspiring people to share!
Get involved: http://typo3.org



More information about the TYPO3-english mailing list