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 call

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 call.

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) Resources then Manage Resources. 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 call in a page with whatever is returned by the snippet. When we put a call to our snippet on a page, 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 call somewhere in the content field of the create/edit document page:

[[MySnippet]]

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

Save the document and then preview it by right-clicking on the document in the document 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 call.

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 Parameters

Now that you've created a snippet, let's try controlling its behavior by adding parameters to the snippet call. A snippet call with parameters looks like this:

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

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

Notice that the parameter 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 parameters to tell the snippet how many lines to print and, optionally, to add some text at the end.

Replace the snippet call you used above, with the new one with the parameters.

Now, we have to change our snippet code to make it use the parameters. Replace the snipppet 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 parameters sent in a MODx snippet call 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 parameter is not equal to "" (nothing, aka an empty string), do the stuff in the curly braces. In other words, if the snippet call sent us something in the $addText parameter, do the following.

In the curly braces of the fourth 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 call, 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 parameters in the snippet call and watch what happens to the output when you preview the page.

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

 

Useful Snippet Links

Installing and using existing snippets.

Modx Wiki snippet page.

Creating snippets (guidelines and howto)

Thank you for visiting BobsGuides.com

  —  Bob Ray