In this hands on, we will create a more complex loop that uses an array of structures.
Tags Used: <cfscript>, <cfloop>, <cfoutput>
Functions Used: arrayAppend
- Open the /www/portfolio.cfm file in your code editor.
- At the top of the file, create open and closing <cfscript> tags.
- Inside the <cfscript> tags create a variable myPortfolio and instantiate an empty array.
-
Your code should look similar to this:
<cfscript> myPortfolio = []; </cfscript>
-
Once you have an empty array, you need to populate it with some data. Below the variable declaration, write the following line of code:
arrayAppend(myPortfolio,{title='',website='',image='',description=''});
- Add this line 2 more times.
-
Provide information for all 3 structures. Your code should look similar to this:
<cfscript> myPortfolio = []; arrayAppend(myPortfolio,{title='Title 1',website='http://www.website1.com',image='portfolio1.png',description='Description 1'}); arrayAppend(myPortfolio,{title='Title 2',website='http://www.website2.com',image='portfolio2.png',description='Description 2'}); arrayAppend(myPortfolio,{title='Title 3',website='http://www.website3.com',image='portfolio3.png',description='Description 3'}); </cfscript>
- Go to the comment Start Portfolio.
-
Once the array has been populated you can loop over it and output its data. Below the comment, create a <cfloop> tag with the following attributes:
- array: #myPortfolio#
- index: portfolio
- Add a closing </cfloop> tag after the first closing </li> tag.
- Replace the value of the href attribute with #portfolio.website#.
- Replace the value of the title attribute with #portfolio.title#.
- Replace the src attribute of the <img> tag with assets/images/portfolio/#portfolio.image#.
- Replace the contents of the <h5> tag with #portfolio.title#.
- Replace the contents of the <p> tag with #portfolio.description#.
- Delete the remaining 2 <li> tags that are outside of the <cfloop>.
- Wrap the <cfloop> tag with an opening and closing <cfoutput> tag.
-
Your code should look similar to this:
<ul id="portfolio-list"> <!-- Start Portfolio --> <cfoutput> <cfloop array="#myPortfolio#" index="portfolio"> <li>
<div class="left"> <a href="#portfolio.website#" title="#portfolio.title#" class="viewDetail "> <img src="images/assets/small/#portfolio.image#" alt=" " border="0" /> <h5>#portfolio.title#</h5> </a> </div> <div class="right"> <p> #portfolio.description# </p> </div> </li> </cfloop> </cfoutput>
</ul>
- Load the /www/portfolio.cfm page in your browser; notice that the contents from the struct is being displayed.
- Update the contents of the structs with more relevant information.
- Add 2 new portfolio items.