Quick ColdBox / i18n tip
Today I needed to update a custom tag we use to display form fields in a ColdBox app to treat the labels as i18n resource keys. Normally in a view you can just call getResource(key) and get back the translated value based on the current locale. Simple. Part of what makes ColdBox great for international apps!
However, you can't call getResource() inside a custom tag called from a view. You might think you can just do caller.getResource(key) but that fails with an exception that the variable controller is not defined. That's because your views run in the context of a CFC and the custom tag has its own context.
I initially came up with a slightly complicated way to pass things to the custom tag but I ended up having to make getResource() public in ColdBox's FrameworkSuperType.cfc. Not ideal. It worked but it was clearly a hack.
I complained to Luis about how hard this seemed to be and he sent me the following code snippet to use in a custom tag:
<cfset variables.controller = caller.controller />
... caller.getResource(key) ...
Remember that you're in the context of a CFC in your view? Well, getResource() is in the variables scope and it, in turn, references controller - which is in the variables scope of the view... or rather the context that the view is executed in. So by setting variables.controller in the custom tag, the call to caller.getResource() finds it and runs properly.
It's still a bit of a hack in my opinion but it's slightly more elegant than what I was trying to do so thank you Luis.
I'm posting it here so a) I can find it again in future and b) others may benefit from this.
Tags: coldbox · coldfusion