Displaying a random image/banner on your umbraco site 9
First some info on the setup:
After installing runway to get a basic site up and running I created a folder in the media section and added several images
On my homepage document type I added a ‘media picker’ property called ‘Pictures’. There I’ll select the media picture folder.
All that’s left now is to write some xslt that will select a random image from the media folder.
<?xml version=”1.0″ encoding=”UTF-8″?>
<!DOCTYPE xsl:Stylesheet [ <!ENTITY nbsp “ ”> ]>
<xsl:stylesheet
version=”1.0″
xmlns:msxsl=”urn:schemas-microsoft-com:xslt”
xmlns:xsl=”http://www.w3.org/1999/XSL/Transform”
xmlns:msxml=”urn:schemas-microsoft-com:xslt”
xmlns:umbraco.library=”urn:umbraco.library”
xmlns:myFuncs=”urn:my-scripts”
exclude-result-prefixes=”msxml myFuncs umbraco.library”>
<xsl:output method=”xml” omit-xml-declaration=”yes” indent=”yes”/>
<xsl:param name=”currentPage”/>
<xsl:variable name=”imageRoot”
select=”$currentPage/ancestor-or-self:: node[@level = 1]/data [@alias = ‘Pictures’]”/>
<msxsl:script implements-prefix=”myFuncs” language=”JavaScript”>
<![CDATA[
var myArray = new Array();
function random(){
var index = Math.floor(Math.random() * myArray.length);
return myArray [index];
}
function addtoArray(item){
myArray.push(item);
}
]]>
</msxsl:script>
<xsl:template match=”/”>
<!– start writing XSLT –>
<xsl:call-template name=”buildArray”>
<xsl:with-param name=”arrayNodes”
select=”umbraco.library:GetMedia($imageRoot, ‘true’)/node/data[@alias=’umbracoFile’]”/>
</xsl:call-template>
<xsl:value-of select=”myFuncs:random()”/>
</xsl:template>
<xsl:template name=”buildArray”>
<xsl:param name=”arrayNodes”/>
<xsl:for-each select=”$arrayNodes”>
<xsl:value-of select=”myFuncs:addtoArray(string(./text()))”/>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
This snippet will output the relative url of a random picture from inside the selected media folder ( like /media/44/dsc00033.jpg ).
RandomPicture xslt: download