Developing for Modx outside of the Manager
Thursday April 15th, 2010Modx is a great platform with a ton of cool features and immense flexibility. Despite that, when I was first beginning to use it I found the prospect of having to write all of my code inside of the Modx Manager a major pain-point.
Today I’m going to explain how to get your templates out of the Manager and into the editor of your choice.
First of all, we need to define a single snippet inside of the manager that will allow us to reference files in our Modx installation. Create a new snippet, name it accordingly (I use external_template) and then enter the following code:
<?php
$file = isset ( $file ) ? $modx->config['base_path'] . $file: '';
if ( $file && file_exists ( $file ) )
{
include "$file";
return '';
}
$modx->sendErrorPage();
?>
This snippet accepts a single parameter ($file) which is the relative location of the template you wish to use. With that parameter the snippet looks for $file and if it is found, it is included onto the page. If the file is not found, a 404 is returned.
With our snippet successfully defined we can now create a new template and use it to include a template file defined elsewhere.
[[external_template?file=`assets/templates/template-directory/homepage.php`]]
In the example above I am referencing homepage.php from /template-directory (where template-directory is created by you and named appropriately). Provided the file exists, Modx will now use its contents as the contents of our new template.
It is important to note that when using this approach, not only have we removed the template from the Manager, but it also maintains the ability to use template variables, chunks and other snippets inside of our external file.
Thanks to the friendly people over at the Modx forums for actually posting the snippet used above. I’ve only tried to provide a context under which to use it and explain its usefulness.