I often find myself in need of some quick PHP in my templates, but the only way to do that is to make a snippet. Snippets are great for reusable code, but what if I just want one line of PHP in one place only?
For example, I like to have dynamic years in my copyright notices so I don’t have to remember to change them every year. Here’s how I’d normally do it:
Copyright © <?php echo date('Y') == '2010' ? '2010' : '2010-' . date('Y');?> Site Name. All rights reserved.
To make that more clear, if the year is still 2010, then I just want the copyright to show the year 2010:
Copyright © 2010 Site Name. All rights reserved.
However, once it’s no longer 2010, the copyright needs to show a range of years:
Copyright © 2010-2011 Site Name. All rights reserved.
The specifics aren’t all that relevant to this post, but I just wanted to clarify what the code does.
Now, specifics aside, my point is that to do this in MODx, I have to make a snippet with the one line of PHP code just so I can use it in that one place and that one place only. I guess you could argue that we’re separating content from logic, but it just feels like a lot of extra work, both for writing the code and being able to read the code when I come back to look at it some other time.
So, what I’m proposing is some sort of anonymous snippet where you define the snippet code right in the template, chunk, or resource where it’s being used. By "anonymous snippet," I’m thinking along the same lines as an
anonymous function. For a quick refresher, an anonymous function is something like in this JavaScript example:
var someFunction = function() {
alert("Output some text.");
};
someFunction();
The idea is that you can create a nameless function at runtime right where you need it. My idea for snippets is similar, but there’d be no variable involved--just the snippet. I don’t know if it’d use a snippet tag or some new tag, but it might look something like this:
[[[<?php
echo 'Since MODx Revolution supports multi-line snippet calls, writing the code would be just like when you're creating an actual snippet.';
?>]? &also=`parameters could still be used like normal`]]
For my example at least, the snippet code goes inside a third set of square brackets, and the code surrounded by that pair of brackets replaces what would normally be the name of the snippet. That would allow everything else to be exactly the same. You would add the question mark if you had parameters, and parameters would of course work exactly the same way.
Does that make sense? What are your thoughts? I think this could be awfully useful for people like me who want to use PHP for little enhancements like my dynamic copyright year without creating a whole new snippet every time.
(By the way, I realize that this would probably only be feasible in Revolution.)