ColdBox Viewlets: Nifty Little Feature

I was chatting with Luis the other day and I had asked a question about how he would handle a certain situation using ColdBox. He promtly replied, “Viewlets!”.
Viewlets? Why havent I heard of viewlets? I have read most of the documentation on the ColdBox wiki, seriously, probably 90% of it! Why dont I remember anything about viewlets.
Well, it turns out that Viewlets are discussed on the very bottom of the Layouts and Views Guide. So Luis sent me a link and I headed over to check them out.Viewlets are pretty cool in how they work. Luis describes them as “a self sufficient view”. So what does that mean, well its a view that can be rendered as-is without having to be called from an event handler. So you can use these viewlets in your layout for instance without having to call them from your handlers directly. Lets look at an example:
Heres a simple little viewlet, we will call it userViewlet.cfm and its just going to show the name of the user to us. Ok, so its not really practical but it will get the point accross.

#fname# #lname#

So, the Viewlet can call an event handler? Yep. The first line of the viewlet code actually calls the method getUsername thats part of our Viewlets event handler and makes the data available to the viewlet.
Heres a look at our sample event handler method:


The event handler method does nothing more than call our service layer using the IOC plugin and runs the query for us then sticks that query into the rc scope to use in our viewlet.
Since viewlets are self sufficient and are responsible for gathering their own data, we can render it anywhere in our application we want like this:

#renderView('viewlets/userViewlet')#

And thats pretty much it. Not a huge concept but it definitely came in handy for building out a Navigation system in my latest project.

Leave a Reply

Your email address will not be published. Required fields are marked *


*