Handling Dynamic Data in MODX: When to Use Snippets Over Templates
Learn how to use MODX Revolution Snippets to bridge the gap between static templates and dynamic data using PHP, script properties, and the MODX API.
25 Aug 2025, 05:34 UTC

The Template Logic Gap
When building a site in MODX Revolution, you quickly hit a wall where standard template tags and chunks aren't enough. You might need to fetch the latest three blog posts, calculate a price based on a user's role, or pull data from an external API. Since MODX templates are primarily for layout, they cannot perform logic like loops or conditional database queries on their own.
The solution is the Snippet. A Snippet is a piece of PHP code that executes on the server before the page is rendered, allowing you to inject dynamic content exactly where you need it using a simple tag.
How Snippets Process Data
Unlike Plugins, which can run at various stages of the MODX lifecycle, Snippets are called explicitly within your templates or chunks using the [[SnippetName]] syntax. When the MODX parser encounters this tag, it pauses the HTML rendering, executes the PHP code associated with that Snippet, and replaces the tag with whatever string the code returns.
To make Snippets reusable, MODX uses Script Properties. These are key-value pairs passed from the template into the PHP code, available inside the Snippet as the $scriptProperties array. This allows one Snippet to handle different data sets depending on where it is placed on the site.
Worked Example: A Custom Resource List
Imagine you need a Snippet that displays a list of resources (pages) based on a specific parent ID. This avoids hard-coding links in your templates. The example below targets MODX Revolution 2.x behavior; verify method names against your installed version, as APIs can differ in MODX 3.
The Snippet Code
Create a new Snippet in the MODX Manager named getRelatedLinks and add the following PHP code:
<?php
// $scriptProperties contains the arguments passed from the template
$parentId = isset($scriptProperties['parentId']) ? (int)$scriptProperties['parentId'] : 0;
if (!$parentId) {
return 'Please specify a parentId.';
}
// Use the MODX API to fetch the parent resource
$parent = $modx->getObject('modResource', $parentId);
if (!$parent) {
return 'Parent resource not found.';
}
$resources = $parent->getMany('Children');
$output = '<ul>';
foreach ($resources as $resource) {
// Skip unpublished pages
if (!$resource->get('published')) {
continue;
}
$url = $modx->makeUrl($resource->get('id'));
$title = htmlspecialchars($resource->get('pagetitle'), ENT_QUOTES, 'UTF-8');
$output .= '<li><a href="' . $url . '">' . $title . '</a></li>';
}
$output .= '</ul>';
return $output;Calling the Snippet in a Template
To use this in your HTML template, call it with the required parentId parameter:
<div class="sidebar-links">
<h3>Related Pages</h3>
[[getRelatedLinks? &parentId=`12`]]
</div>Replace 12 with the actual ID of the parent resource in your site tree. You can find the ID in the MODX Manager resource tree, shown in parentheses next to each resource name.
Verification and Risks
- Verification: Load the page in a browser. If the list appears, the Snippet is working. If the page is blank or shows a PHP error, check the MODX error log in the Manager under Reports > Error Log (menu labels vary slightly by version).
- Permissions: Snippets run with the permissions of the web server user (e.g.,
www-data). Ensure the server has the necessary PHP extensions enabled for any external API calls. - Security: If a Snippet ever processes user-supplied input (query strings, form data), validate and sanitize it before use. The example above escapes output with
htmlspecialcharsand casts the parameter to an integer for this reason. - Risk: Avoid placing heavy database queries inside Snippets that appear on every page (like the footer), as this can significantly increase page load times.
Trade-offs: Performance vs. Flexibility
While Snippets are powerful, they introduce a performance cost. Every uncached [[Snippet]] call triggers PHP execution during the request lifecycle. If a page has 20 different Snippets, the server must process each one before sending the first byte of HTML to the user.
| Approach | Pros | Cons |
|---|---|---|
| Static Chunks | Instant rendering, cached easily. | No logic; must be updated manually. |
| Snippets | Fully dynamic, programmable. | Higher CPU usage, potential for PHP errors. |
| Cached Snippets | Fast delivery after first load. | Content may be stale until cache expires. |
To mitigate performance hits, call the Snippet cached by using the cached tag syntax: [[getRelatedLinks? &parentId=`12`]] is cached by default in MODX Revolution, while the uncached variant [[!getRelatedLinks? &parentId=`12`]] forces fresh execution on every request. Use the uncached form only when the output must reflect real-time state, such as data tied to the current user session.
Closing Action
When deciding whether to write a Snippet, ask if the data changes frequently. If it does, a Snippet is the correct tool. If the data is static, use a Chunk. To start, identify one area of your site where you are manually updating links or text, and replace it with a Snippet that pulls that data programmatically from the MODX API. Then measure: compare page load time with the cached and uncached tag syntax to see the real cost of dynamic execution on your server.
0 replies
A thoughtful contribution can make all the difference. Be the first to share one.