I have several different snippets in my templates that all rely on the return value of another snippet, "getDepartment". Right now each of the snippets that needs that value calls getDepartment... resulting in multiple calls to getDepartment per page, even though its always gonna return the same value on a given page.
I’m not the sharpest knife in the drawer, but I can see where that isn’t very efficient. So I set out to determine how to write it more efficiently.
Since my templates are based on nested chunks, starting with an outermost [[$html]] chunk, I think the most logical/mainstream solution is to do the following:
- Change the template code to [[$html? &dept=`[[getDepartment]]`]]
- Change the calls of the snippets that need that value to [[someDeptSnippet? &dept=`[[+dept]]`]]
Setting the value of $dept in the outermost chunk call should set all the [[+dept]] placeholders, effectively passing $dept as an argument to each snippet. (Right?)
So my question is, is that the best solution? Or is there a better one?
Now my constructive feedback.
It isn’t at all clear to me from reading the documentation on Snippets and Using Snippets that each snippet is saved/cached/access as a function... and has the scope limitation of a function. On first glance at how MODx appears to work, I was under the wrong assumption that I could write & use snippets in the manner that I used to write bad mixed HTML & procedural PHP... define a value $x in one PHP block, then have some HTML, then have another PHP block where I might, say, call a function and pass it the value of $x as an argument. This doesn’t work though, when each block of PHP is itself a function. It took me a long while of wandering in the wilderness to figure that out.
My suggestion, then, is to add something to the core documentation about snippets that 1) addresses the fact that they are going to be converted to functions, and all of the ramifications of that, and 2) provides some direction on how to pass values in the manner I’m looking to do up above. I think this would make the concept of snippets a lot more accessible & less mystical.