Using Custom Tags - Exercise

Contact Us or call 1-877-932-8228
Using Custom Tags - Exercise

Using Custom Tags

Duration: 20 to 30 minutes.

In this exercise, you will create a custom tag that can turn tab-delimited text into an HTML table.

  1. Open CustomTags/Exercises/ProfitLoss.txt in your editor. This is a tab-delimited text file showing a simple profit-loss statement.
  2. Open CustomTags/Exercises/ProfitLoss.cfm in your editor. This file is created for you. It calls the custom tag cf_Text2Table, which you will be working on. Notice that it has both an open and a close tag and that the body of the tag will contain the text from ProfitLoss.txt.
  3. Open CustomTags/Exercises/Text2Table.cfm in your editor. You will write code to turn the body text of the tag (i.e, the text between the open tag and close tag) into an HTML table. Note that you will need to modify the contents of the GeneratedContent variable.
  4. To test your solution, open CustomTags/Exercises/ProfitLoss.cfm in your browser. It should look something like this:

The Text2Table tag requires an end tag. Add code so that the tag exits (use <cfexit>) with an error message if the call does not include an end tag. The resulting page is shown below:

Solution:

CustomTags/Solutions/Text2Table.cfm
<cfparam name="ATTRIBUTES.RowMarker" default="#chr(10)##chr(13)#">
<cfparam name="ATTRIBUTES.CellMarker" default="#chr(9)#">
<cfparam name="ATTRIBUTES.HeaderRow" default="false">

<cfif thisTag.executionMode EQ "end">
	<cfset thisTag.GeneratedContent = TRIM(thisTag.GeneratedContent)>
	<cfsavecontent variable="Table">
	<cfoutput>
	<table border="1">
	<cfset i=1>
	<cfloop list="#thisTag.GeneratedContent#" index="row" delimiters="#ATTRIBUTES.RowMarker#">
		<cfif ATTRIBUTES.HeaderRow AND i EQ 1>
		<tr>
			<cfloop list="#row#" index="cell" delimiters="#ATTRIBUTES.CellMarker#">
				<th>#cell#</th>
			</cfloop>
		</tr>
		<cfelse>
			<tr>
				<cfloop list="#row#" index="cell" delimiters="#ATTRIBUTES.CellMarker#">
					<td>#cell#</td>
				</cfloop>
			</tr>
		</cfif>
		<cfset i = i + 1>
	</cfloop>
	</table>
	</cfoutput>
	</cfsavecontent>
	<cfset thisTag.GeneratedContent = Table>
</cfif>

Challenge Solution:

CustomTags/Solutions/Text2Table-challenge.cfm
<cfparam name="ATTRIBUTES.RowMarker" default="#chr(10)##chr(13)#">
<cfparam name="ATTRIBUTES.CellMarker" default="#chr(9)#">
<cfparam name="ATTRIBUTES.HeaderRow" default="false">

<cfif NOT thisTag.hasEndTag>
	<div style="color:red; font-weight:bold">Warning: Custom Tag Text2Table must have an end tag</div>
	<cfexit>
</cfif>

<cfif thisTag.executionMode EQ "end">
---- C O D E   O M I T T E D ----
</cfif>
Next