Improving the Tutorial: Object- and Query-Driven Partials in CFWheels
Writing a beginner tutorial like the Wheels Hello Database tutorial is tough. There are so many things that you want to do to improve the code. But you also don’t want for the tutorial to be 20 pages long. So you kind of need to let go and leave things where they are.
That said, I have a blog where I can say anything that I want to. Here is one way that I would improve the Hello Database tutorial: through the use of a query-driven partial. I don’t even think that query-driven partials were available in Wheels when I wrote the tutorial, so this blog post can be a double-win.
In the tutorial, we could factor out a few lines into a partial and end up with a little bit less code in our view. Here’s how the table listing all users is written in the tutorial:
As it turns out, the whole
<cfloop> block can be factored out into a partial. But it won’t be a “normal” partial. Instead of passing in a name of a partial to the
includePartial() function, we’ll pass the query object itself.
So now we can replace the loop and its contents with this line:
Much tidier. No mixture of CFML and HTML tags.
Because the query object is named
users, Wheels will look for a partial called _user.cfm automatically. In my opinion, this makes naming of the partials very straightforward and almost self-documenting.
Now that the view file is a little cleaner, we put our table row in views/users/_user.cfm. This becomes the contents of the partial:
As you can see, the properties of the query object become available in the
arguments scope. And the partial gets called automatically for each iteration through the record set.
This same partial would also work if we passed
includePartial() a single
user model object as well. Pretty powerful, reusable stuff.