Beginners guide on how to include snippets in the document/page

From MODx Wiki

Jump to: navigation, search

Please refer to the Snippets Overview page for a more thorough discussion on Snippets.

A snippet is just that: a snippet of PHP code. You can use snippet calls to include this piece of code wherever and whenever you want in your site. All that these snippets do is output something. That something can be a simple little bit of text, or it can be a huge and complete HTML document.

Here is a very simple example which will teach you how to create a snippet and then include it in a document or page (which MODx also sometimes likes to call ‘resources’).

  1. Login to the admin panel at www.yoursite.com/manager
  2. Go to Resources > Manage Resources > Snippets
  3. Select 'New Snippet'
  4. Give your snippet a name, e.g. 'hello_world' (without the quotes)
    To reference this snippet on a page (e.g. within a template or in a chunk), you would write [[hello_world]] on the page. That causes the snippet to execute and its output will replace the double-square-bracket placeholder.
  5. Write some code for your snippet. Here's that very simple example that we were talking about—a short piece of PHP code.
  1. <?php
  2. echo 'Hello world!';
  3. ?>

Save the snippet. Now head back to one of your pages and edit it. Now, paste <tt>[[hello_world]]</tt> text into the content field and save the page. You should paste this in without any RTE (rich text editor, for example TinyMCE and FCKEditor) turned on, as these might add formatting to the code that stops it working. To turn the RTE off permanently for a particular page, go to the Settings tab and untick ‘Rich text’.

When you visit the page, you should see the text "Hello world!".

Right. And why is this useful, exactly?

Using snippets means that you can do anything that PHP can do, anywhere on your site. That amounts to just about anything you could ever need.

Of course, you won't want to write a new snippet every time you want to do something clever, so this is where MODx's addons collection comes in. You will find snippets here that do just about everything you might want—news systems, menus, search etc. In fact, some of the more important ones, like Wayfinder (menu creator), Ditto (primarily a news system, although it stretches to lots of other things) and AjaxSearch (clue's in the name), are so useful that they are included in the default MODx installation.

Personal tools