Creating and Using MODX Snippets

There will eventually be a deeper explanation of snippets here. For now, here a brief explanation of snippets, a brief tutorial in which you create your own snippet, and some useful snippet-related links.

What are snippets for? 

As we said on the main MODx page, snippets are for when you need dynamic content on a page. The snippet code actually generates the content "on-the-fly" and returns it for insertion in place of the snippet tag

Suppose you wanted to have a web page called "This Day in History" that showed important events that happened on today's date. You could write a snippet in PHP that queried a database of events for those that happened on today's date, generated the content for your page, and returned it for insertion in place of the snippet tag.

Creating Your Own Simple Snippet

This will sound odd, especially if you are not an experienced PHP coder, but the best way to understand snippets is to create one. The existing snippets in MODx may do everything you want, but you'll understand them much better (and faster) if you first create a snippet of your own. This brief tutorial will walk you through the creation of a simple snipppet which we'll edit a little so you can see how snippets actually work.

The "This Day in History" snippet is beyond the scope of this section so let's start with something much simpler. Our first snippet will simply print some text on the screen. Of course you could do this with a chunk, but we're learning about snippets so we'll do it with a snippet instead. You should definitely work through the Getting Started page on this site (if you haven't done so already) before continuing. You'll also need a working MODx site where you can create your snippet.

Create a snippet called MySnippet by selecting (from the tabs at the top of the screen in the MODx Manager) Elements then Manage Elements. Select the Snippets tab on the right if it's not already selected and click on New snippet. In the snippet name field, put MySnippet. You can fill in a description if you like, but it's optional.

Next, paste the following code into the code window on the snippet page:


$output = "<p>This is the first line of my snippet.</p>";
$output .= "<p>This is the second line of my snippet.</p>";
$output .= "<p>This is the third line of my snippet.</p>";
return $output;

Make sure the code is pasted between the opening (<?php) and closing (?>) PHP tags. These tags tell the server that that section should be processed as PHP code.

What's going on in this PHP code? Variables in PHP always start with a dollar sign ($) so the only variable we are using is $output. Some snippets have lots of variables but this is a very simple snippet.

In the first line of our snippet, we are assigning the string between the quotation marks to our variable. Once the PHP processor is beyond that line, the variable $output equals whatever we put between the two quotation marks on the first line. Notice that the line ends with a semicolon (";"). All statements in PHP must end with a semicolon.

In the second line, we see something new. After the variable, we have a ".=" instead of a simple equals sign. This is the PHP concatenation operator. What it does is tack whatever follows it on to the end of the existing variable. If we had used an equals sign here, the second string would replace the first one and the first string would be lost. By using the ".=" operator, however, our variable ($output) is now set to the first string followed by the second one. On the third line, we add a third string onto the end of the variable and in the fourth line, we return that variable from the snippet.

MODx will replace the snippet tag in a page with whatever is returned by the snippet. When we put a call to our snippet on a page with a snippet tag, we should see all three of the strings we used here. Let's try it out. (Be sure to save your snippet before moving to the next step.)

Create a document in MODx (or use an existing one) and put the following snippet tag somewhere in the Content field of the Create/Edit Resource panel:

[[MySnippet`]]

Remember that snippet names are case-sensitive, so be sure to type the name the same way when you enter the snippet tag as you did when you created the snippet. If you don't, MODx will replace the snippet tag with nothing at all.

Save the document and then preview it by right-clicking on the document in the Resource tree at the left of the MODx Manager screen and selecting Preview document. You should see the three lines, each in a separate paragraph, where you placed the snippet tag.

Congratulations, you've just created your first snippet. Try editing the three lines of the snippet or adding new lines. Be careful, though, because an incorrectly formatted line of PHP code will often make MODx produce a completely blank page when the PHP parser gets confused. Each line must have matched quotation marks and a semicolon at the very end.

Controlling Your Snippet with Properties

Now that you've created a snippet, let's try controlling its behavior by adding properties (formerly called "parameters") to the snippet tag. A snippet tag with properties looks like this:

[[MySnippet? &howMany=`2` &addText=`Add This`]]

The properties are just pieces of information that are sent to the snippet. In this case we have two properties, howMany, which is set to 2 and addText, which is set to the string "Add This."

Notice that the property values are enclosed in back-ticks, not single quotes. The back-tick is usually on the same key as the tilde (~). Forgetting to use back-tics is the most common error for new snippet users.

We're going to use our properties to tell the snippet how many lines to print and, optionally, to add some text at the end.

Replace the snippet tag you used above, with the new one with the properties.

Now, we have to change our snippet code to make it use the properties. Replace the snippet code in your MySnippet snippet with the following code:


if ($howMany >= 1) {
    $output = "<p>This is the first line of my snippet.</p>";
}
if ($howMany >= 2) {
    $output .= "<p>This is the second line of my snippet.</p>";
}
if ($howMany >= 3) {
    $output .= "<p>This is the third line of my snippet.</p>";
}
if ($addText != "") {
    $output .= "<p>" . $addText."</p>";
}

return $output;

This code may look complicated at first, but it's really pretty simple. The properties sent in a MODx snippet tag actually show up as variables in the snippet code. So &howMany is referred to in the snippet as $howMany and &addText shows up as $addText.

An "if" statement just says: If the part in the parentheses is true, do whatever is inside the following curly braces, otherwise don't do anything. There could be a number of PHP statements between the curly braces that would all get executed if the part in the parentheses was true.

The ">=" operator just means "greater than or equal to" so the first "if" statement just says: If the value of $howMany is great than or equal to 1, print that first line. The next two "if" statements are basically the same but they're testing for a different value of $howMany.

In the fourth "if" statement, we see the "!=" operator which combines the "not" operator ("!") with the equals sign. It says: If the value of the $addText property is not equal to "" (nothing, aka an empty string), do the stuff in the curly braces. In other words, if the snippet tag sent us something in the $addText property, do the following.

In the curly braces of the if statement, we see something else new. The dot operator is another kind of concatenation operator. It just tells PHP to put several strings together and treat them as a single string. In this case, we're using them to splice together a paragraph tag, the value of $addText sent in the snippet tag, and an end paragraph tag into a single string. The spliced string is then tacked on to the end of the $output variable (but only if something was sent in the $addText variable).

When you get tired of looking at the new snippet code, save the snippet and preview the page again. You should see the first two strings but not the third and you should see "Add this" as a third line on the page. Try changing the properties in the snippet tag and watch what happens to the output when you preview the page.

By now, you should understand the basics of snippet tags and snippet properties. Some of MODx's popular snippets have many more properties, and some MODx snippet properties contain chunk names instead of literal values, but the principle is the same for all snippets. Properties are just pieces of information that tell the snippet how to do its job.

Default Properties and Property Sets

In MODx Revolution, snippet can have default properties and property sets. They are shown on the Properties tab when editing the snippet. Their values can be changed in the grid on the Properties tab. They work exactly like the properties we sent in the snippet tag above. Properties set in a property set will override any default properties with the same name. Properties sent in a snippet tag will override all other properties with the same name, so they have the highest priority.

 

Useful Snippet Links

Bob's Guides Snippet FAQ

snippet tag Anatomy.

MODX Revolution Snippets.

Modx Wiki snippet page.

Creating snippets (guidelines and howto)

 

My book, MODX: The Official Guide - Digital Edition is now available here. The paper version of the book is available from Amazon.

If you have the book and would like to download the code, you can find it here.

If you have the book and would like to see the updates and corrections page, you can find it here.

MODX: The Official Guide is 772 pages long and goes far beyond this web site in explaining beginning and advanced MODX techniques. It includes detailed information on:

  • Installing MODX
  • How MODX Works
  • Working with MODX resources and Elements
  • Using Git with MODX
  • Using common MODX add-on components like SPForm, Login, getResources, and FormIt
  • MODX security Permissions
  • Customizing the MODX Manager
  • Using Form Customization
  • Creating Transport Packages
  • MODX and xPDO object methods
  • MODX System Events
  • Using PHP with MODX

Go here for more information about the book.

Thank you for visiting BobsGuides.com

  —  Bob Ray