Snippets


Overview

Snippets are the method by which MODx allows you to run dynamic PHP code in any of your pages.

What is a Snippet?

According to one definition, a "snippet" is "a short reusable piece of computer source code". Some people have a hard time distinguishing this from a "chunk", so a helpful mnemonic might lie in the p's... as in "PHP", e.g. sni-"P(h)P"-et.

Simple Example

Here's the perfunctory super-basic example of what a Snippet might look like:

<?php
return "Hello, World!";
?>

If you named this "helloWorld", you could call this snippet by using [[helloWorld]] in your documents, templates, or Chunks.

Passing Values Into a Snippet

Snippets can take input values using a modifed CGI web-form type notation.  For example, if your Snippet looks something like this:

<?php
return 'My input was: ' . $Input;
?>

You might call it using something like this:

[[my_snippet_name? &Input=`Hello World`]]

Notice that the variable names in the calling bit need to match the variable names in the Snippet EXACTLY (case matters... i.e. 'Input' not 'input'). Secondly, don't forget the '&' in front of the would be variable names. And last but most certainly not least, take note that those are backticks, not single quotes!

Recommended Methods and Tips

<p>This is a horrible mixture of HTML and PHP</p>
<?php
return "<p>and PHP!&nbsp; Don't try it!&nbsp; It's bad architecture and it won't work!!</p>";
?>

You'll find that MODx will append PHP tags to beginning and end of the snippet, creating an invalid syntax, e.g.

<?php <?php //something here ?> ?>

If you need to do something like this, use a Chunk - separate the PHP into a Snippet, load its output into a placeholder with the modx API placeholder functions, and include the Snippet's placeholders in the Chunk.

See Also


Browse Space

- Pages
- News
- Labels
- Attachments
- Bookmarks
- Mail
- Advanced

Explore Confluence

- Popular Labels
- Notation Guide

Your Account

Log In

Other Features

Add Content