Chris Peterson hit me up on IM today with the following question. (I've simplified it a bit for the blog post.)
I've got a set of custom tags where I'm passing data to the 'wrapper' and I'd like the custom tags inside the wrapper to have access to it. I can make this work by using the Request scope, but that feels wrong. Is there a better way?Sure! Let's look at a simple example first. Imagine I've got two custom tags, parent and child, and I can call them like so:
<cf_parent lastname="Camden"> <cf_child firstname="Jacob"> <cf_child firstname="Lynn"> <cf_child firstname="Noah"> </cf_parent>
Within the child custom tag, I want to output the name of the child like so:
<cfparam name="attributes.firstname" default="Nameless">
<cfoutput> My name is #attributes.firstname#. <p/> </cfoutput>
This works fine and returns the first name of each of the child tags, but how would we get the full name? As Chris says, the Request scope could definitely be used to solve this problem, but there is a much simpler way to do it: GetBaseTagData().
This function allows you to call any parent custom tag (and not just necessarily the immediate parent) and fetch all of the data in the parent tag. So for example, by adding this one line to child.cfm:
<cfset parentData = getBaseTagData("cf_parent")>
I get a structure that contains any variable or attributes that were created in parent.cfm. If I include this simple line in parent.cfm:
<cfparam name="attributes.lastname" default="Nameless">
I can then use this modified version of child.cfm:
<cfparam name="attributes.firstname" default="Nameless"> <cfset parentData = getBaseTagData("cf_parent")>
<cfoutput> My name is #attributes.firstname# #parentData.attributes.lastname#. <p/> </cfoutput>
I should point out that it is also possible for children tag to share their data with parents. In the past I've done that when the parent tag is the "main" logic for whatever I'm doing and the children tag simply provide metadata. In that form, the children tag simply pass up their info to the parent and the parent makes use of it. If you have even seen me use a custom tag called datatable in my applications, that is an example of it.