Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
70 changes: 7 additions & 63 deletions en/building-sites/elements/chunks.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,102 +5,46 @@ _old_id: "56"
_old_uri: "2.x/making-sites-with-modx/structuring-your-site/chunks"
---

Chunks are bits of static text which you can reuse across your site, similar in function to include files or "blocks" in other content management systems. Common examples of Chunks might be your contact information or a copyright notice. Although Chunks cannot contain any logic directly, they can however contain calls to [Snippets](extending-modx/snippets "Snippets"), which are executable bits of PHP code which produce dynamic output.
A Chunk is reusable static text, such as a contact line or a copyright notice. A Chunk cannot contain logic. It can call a [Snippet](extending-modx/snippets "Snippets").

## Create

Before you can use a Chunk, you must first create and name one by pasting text into the MODX manager (Elements --> Chunks --> New Chunk):
Before you can use a Chunk, create one from the Elements tree: **Elements** → **Chunks** → **Create Chunk**.

![](chunk_example.jpg)

## Usage

To use the Chunk, you reference it by name in your templates or in your page content.
Call the Chunk by name in a Template or in Resource content:

``` php
[[$chunkName]]
```

That reference is then replaced with the contents of the Chunk.
MODX replaces that tag with the Chunk contents.

You can also pass properties to a Chunk. Say you had a chunk named 'intro' with the contents:
You can pass properties. For a Chunk named `intro`:

> Hello, `[[+name]]`. You have `[[+messageCount]]` messages.

You could fill those values with:

``` php
[[$intro? &name=`George` &messageCount=`12`]]
```

Which would output:

> Hello, George. You have 12 messages.

You could even take it one step further, by adding a [Template Variable](building-sites/elements/template-variables "Template Variables") that allows the user to specify their name per Resource:
Placeholders can also come from a [Template Variable](building-sites/elements/template-variables "Template Variables"):

``` php
[[!$intro? &name=`[[*usersName]]` &messageCount=`[[*messageCount]]`]]
```

or in the Chunk itself:
Or put the Resource tags in the Chunk:

``` php
Hello, [[*usersName]]. You have [[*messageCount]] messages.
```

## Processing Chunk via the API

Chunks are also frequently used to format the output of Snippets. A Chunk can be processed from a Snippet using the process() function; for example, given the following Chunk named 'rowTpl':

``` php
<tr class="[[+rowCls]]" id="row[[+id]]">
<td>[[+pagetitle]]</td>
<td>[[+introtext]]</td>
</tr>
```

the following Snippet code retrieves it and processes it with an array of properties for all published Resources, and returns formatted results as a table, setting the class to "alt" if for even rows:

``` php
$resources = $modx->getCollection('modResource',array('published' => true));
$i = 0;
$output = '';
foreach ($resources as $resource) {
$properties = $resource->toArray();
$properties['rowCls'] = $i % 2 ? '' : 'alt';

$output .= $modx->getChunk('rowTpl',$properties);
$i++;
}
return '<table><tbody>'.$output.'</tbody></table>';
```

### Modifying a Chunk Via the API

Chunks can also be manipulated by the MODX API:

``` php
<?php
/* create a new chunk, give it some content and save it to the database */
$chunk = $modx->newObject('modChunk');
$chunk->set('name','NewChunkName');
$chunk->setContent('<p>This is my new chunk!</p>');
$chunk->save();

/* get an existing chunk, modify the content and save changes to the database */
$chunk = $modx->getObject('modChunk', array('name' => 'MyExistingChunk'));
if ($chunk) {
$chunk->setContent('<p>This is my existing chunks new content!</p>');
$chunk->save();
}

/* get an existing chunk and delete it from the database */
$chunk = $modx->getObject('modChunk', array('name' => 'MyObsoleteChunk'));
if ($chunk) $chunk->remove();
?>
```

## See Also

- [modChunk](extending-modx/core-model/modchunk "modChunk")
4 changes: 2 additions & 2 deletions en/building-sites/elements/plugins.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,6 @@ sortorder: "5"
note: "This document is a stub and needs to be expanded."
---

Plugins are PHP code that fire when _Events_ are fired. The MODX core has lots of events that fire at different points during the parsing and interacting with objects in the manager.
A plugin is PHP that runs when an event fires. A plugin you write runs when **Deactivate Plugin** is unchecked and the event is checked on the **System Events** tab.

When building sites, you'll usually only use existing plugins that are available as installable packages, but if you're confident in PHP you can also write your own.
When you build a site you will mostly install plugins as packages. If you are comfortable with PHP, you can write your own.
16 changes: 8 additions & 8 deletions en/building-sites/elements/snippets.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,11 @@ _old_id: "335"
_old_uri: "2.x/making-sites-with-modx/structuring-your-site/using-snippets"
---

[Snippets](extending-modx/snippets "Snippets") are MODX's answer to inline PHP code. They provide customizable dynamic content, such as menus, blog or news listings, search and other form-based functionality and anything else that your site needs to generate on-demand.
A [Snippet](extending-modx/snippets "Snippets") is PHP that the page runs when it is requested. Typical results are a menu, a news list, or a search form.

## Using a Snippet

Once you have a Snippet installed, you can use it simply by putting its tags in your template, a chunk or TV, or a document's content wherever you want the Snippet's output to be displayed.
Put the Snippet tag where its output should appear: in a Template, a Chunk, a TV, or Resource content.

``` php
[[MySnippet]]
Expand All @@ -23,31 +23,31 @@ If you expect the snippet code to be dynamic for different users, you can also c

## Snippet Properties

Snippets can have [Properties](building-sites/properties-and-property-sets "Properties and Property Sets"), which can be passed in the Snippet call, like so:
Pass [properties](building-sites/properties-and-property-sets "Properties and Property Sets") in the Snippet call:

``` php
[[!Wayfinder? &startId=`0` &level=`1`]]
```

You can also aggregate these Properties into a [Property Set](building-sites/properties-and-property-sets "Properties and Property Sets"), which is a dynamic collection of properties that can be attached to any Snippet (or Element for that matter). This allows you to share common property configs in a snippet call in one place.
A [property set](building-sites/properties-and-property-sets "Properties and Property Sets") stores those properties under one name. Attach the set to the Snippet (or to another Element).

Say you had a Property Set called 'Menu' with `startId` set to 0 and `level` set to 1:
Say you had a Property Set called `Menu` with `startId` set to 0 and `level` set to 1. Attach that set to the Snippet. Then:

``` php
[[!Wayfinder@Menu]]
```

would then load those properties automatically into the Snippet. And even those properties can be overridden:
That call loads those properties into the Snippet. If the set is not attached to this Snippet, `@Menu` adds nothing. Properties in the tag still override the set:

``` php
[[!Wayfinder@Menu? &level=`2`]]
```

which would override the set's value on `level` of 1, setting it instead to 2.
sets `level` to 2 instead of the set's `1`.

## Installing Snippets

You can also download and install Snippets via [Package Management](extending-modx/transport-packages "Package Management"). See the tutorial on [installing a Package](building-sites/extras "Installing a Package") for more information.
Install a Snippet from [Package Management](extending-modx/transport-packages "Package Management"). Steps: [installing a package](building-sites/extras "Installing a Package").

## See Also

Expand Down
77 changes: 54 additions & 23 deletions en/building-sites/elements/static-elements.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,46 +4,77 @@ _old_id: "1753"
_old_uri: "2.x/developing-in-modx/basic-development/static-elements"
---

Since MODX Revolution 2.2 you can create Static Elements to make managing your elements easier. This feature is available for all elements, including Templates, Chunks, Snippets and Plugins.
A Template, Template Variable, Chunk, Snippet, or Plugin can take its source from a file. Saving the element in the Manager writes that file.

A static element is an element which gets its content from a file. When edited via the manager, the file will get updated. Similarly, when you edit the file via an IDE, it will get updated in MODX the next time the element is requested.
## Creating a static element

## Creating a Static Element
Check **Is Static**, choose a **Media Source**, and put the file path in **Static File**. The path is relative to that media source.

To create an element as a static element, simply check the _Is Static_ checkbox, select a Media Source, and add the path to the file relative to that media source to the _Static File_ input. You can also click the icon in the _Static File_ input to open the MODX Browser to select the file, rather than entering it manually.
The folder icon in **Static File** opens the browser only when the media source is a file source. With **(None)**, the field is plain text. Type the path yourself.

![](static-template.png)

This process is the same for all types of elements.
The same fields are on every element type.

### Creating a Static Element without a Media Source
### Media source (None)

Alternatively, you can create a static element and select `None` as the Media Source.
Choose **(None)** in **Media Source** when you want to type a path yourself.

In this case, you can add a path relative to the MODX core components path (`MODX_CORE_PATH . 'components/'`) in the _Static File_ input, or you can create a system setting with the key `element_static_path` which will set the location your paths will be relative to.
An absolute path is used as written when that file already exists. If the file is not there yet, MODX creates it under the system setting `element_static_path`. That setting is not included with MODX. Create it, or new files go in `core/components/`.

You can also use absolute paths when the media source is set to `None`.
`static_elements_basepath` is not that folder. It is the prefix written into **Static File** when automatic paths are on.

## Files vs. Database
## Files and the database

Please be aware that MODX still stores the contents in the database as well, in order for the element to be processed normally. MODX only checks the contents of the file when the element is requested uncached, so be sure to clear the cache while developing. For this reason you might find static elements to be most useful when working on uncached snippets or plugins, and slightly less useful on templates and chunks.
MODX still keeps a copy of the source in the database. A cached Chunk or Template inside a cached Resource keeps the old source until you clear the cache or call the element uncached (`[[!$name]]`). A Snippet or Plugin that actually runs picks up a newer file by its modification time. Plugins are not cached.

To improve the editing experience with static elements, there are several Extras available that can help automatically create the elements in the MODX database, or that automatically clear the cache for you.
Some extras create the element for you, or clear the cache. This page does not name them.

## Automatic static elements creation
## Automatic static files

As of MODX 2.7 it is possible to automate the process of generating static elements in the core. It takes away the manual steps of creating a static element, such as marking an element as static, selecting your static elements media source and it automatically generates the filepath name for your static file.
The Manager can mark the element static and fill in **Static File** for you.

When an element is removed or renamed, the associated file is removed as well.
Open **Admin** → **System Settings** and filter by **Static Elements**.

### Setting up automatic static elements
1. Turn on `static_elements_automate_templates`, `static_elements_automate_tvs`, `static_elements_automate_chunks`, `static_elements_automate_snippets`, or `static_elements_automate_plugins` for the types you want.
2. Set `static_elements_default_mediasource` to the media source id you want on new elements.
3. Set `static_elements_basepath` to the prefix inside that media source, for example `components/static/elements/`. With **(None)**, do not start this prefix with `components/` or the new file is created under `core/components/components/`.
4. Optionally set `static_elements_default_category`.

1. Go to System > System Settings. Select the Static Elements topic.
2. Turn on automating static elements for each element type you want to use automate the static elements workflow for. For example, enable the `static_elements_automate_snippets` setting to use it for snippets, and `static_elements_automate_chunks` to use it for chunks.
3. Select the default media source to use for static elements in the `static_elements_default_mediasource` setting.
4. Provide your static elements basepath, which is where the files will go, in the `static_elements_basepath` setting. For example: `components/static/elements/`.
5. Optionally select a default category to use for your static elements in the `static_elements_default_category` setting.
### Where the file is written

### File structure
The path is `{basepath}/{type}/{category}/{name}{suffix}`.

Files will be created at the path: `{static_elements_basepath}/{type}/{category}/{filename}.{extension}` within the specified media source. For example: `components/site/elements/chunks/html/footer.chunk.tpl`.
The name and the category are lowercased, and spaces become `-`. A `--` in the category becomes `/`.

| Type | Suffix |
| --- | --- |
| templates | `.template` plus `static_elements_html_extension` (default `.tpl`) |
| tvs | `.tv` plus the same extension |
| chunks | `.chunk` plus the same extension |
| snippets | `.snippet.php` |
| plugins | `.plugin.php` |

`static_elements_html_extension` is not added to Snippets or Plugins.

A Chunk named `my-footer` in the category `html`, with base path `components/site/elements/` and a file media source, is stored as `components/site/elements/chunks/html/my-footer.chunk.tpl`.

### When the file is deleted

With automation on for that type, saving a new path removes the previous file. Deleting the element removes the file only when automation is on and the media source is a file source. With **(None)**, the file stays on disk. Delete it yourself. If another element uses the same static file, the file is kept.

After you drag the element to another category, the file can land in a different folder than the form would use. Open the element and save it so the Manager recalculates the path.

## Static element settings

| Setting | Default | What it does |
| --- | --- | --- |
| `static_elements_automate_templates` | `false` | Fill in a static file for new Templates. |
| `static_elements_automate_tvs` | `false` | Fill in a static file for new Template Variables. |
| `static_elements_automate_chunks` | `false` | Fill in a static file for new Chunks. |
| `static_elements_automate_snippets` | `false` | Fill in a static file for new Snippets. |
| `static_elements_automate_plugins` | `false` | Fill in a static file for new Plugins. |
| `static_elements_default_mediasource` | `0` | Media source id written on a new automatic element. |
| `static_elements_default_category` | `0` | Category id written on a new automatic element. |
| `static_elements_basepath` | `''` | Prefix written into **Static File**, inside the chosen media source. |
| `static_elements_html_extension` | `.tpl` | Extension after `.template`, `.tv`, and `.chunk`. |
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ _old_uri: "2.x/making-sites-with-modx/customizing-content/template-variables/bin

The @CHUNK Binding returns the parsed content of any specified Chunk when @CHUNK is used in a Template Variable (TV).

In other words, if @CHUNK Hello is the value of a TV called MyChunk, the following tag in a Template or in the Resource Content field of a Resource will be replaced with the contents of the Hello chunk:
If the TV `MyChunk` is set to `@CHUNK Hello`, this tag in a Template or in Resource content is replaced with the Hello Chunk:

``` php
[[*MyChunk]]
Expand All @@ -22,7 +22,7 @@ In other words, if @CHUNK Hello is the value of a TV called MyChunk, the followi

Binds the variable to a Chunk. `chunk_name` is the Chunk name. The returned value is the parsed Chunk output.

Optional JSON properties (MODX 3.0+) are passed to `getChunk()` as the Chunk placeholders / properties array.
Optional JSON after the Chunk name becomes placeholders in that Chunk.

## Usage

Expand All @@ -36,7 +36,7 @@ With properties:
@CHUNK MycontactForm {"submitLabel":"Send","showTitle":"1"}
```

Invalid JSON after the Chunk name is logged as an error and ignored; the Chunk still runs without those properties.
Invalid JSON after the Chunk name is written to the MODX error log. The Chunk name is not trimmed, so MODX looks for a Chunk whose name includes that tail and does not find it. Valid JSON is still split off and passed to the Chunk.

This binding is similar to the [@RESOURCE binding](building-sites/elements/template-variables/bindings/resource-binding "RESOURCE Binding"), except it binds the TV to a [Chunk](building-sites/elements/chunks "Chunks"). For running PHP, use [@SNIPPET](building-sites/elements/template-variables/bindings/snippet-binding "SNIPPET Binding") instead.

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ _old_uri: "2.x/making-sites-with-modx/customizing-content/template-variables/bin

## What is the @DIRECTORY Binding?

The DIRECTORY binding reads the contents of a directory. This can really useful when you tie it into a List control widget, e.g. if you want to do something like give the user a list of logo images to choose for a page, or choose which mp3 file plays on a particular page. REMEMBER: it returns **ALL** contents of a directory, including all files and all directories - with the sole exception of directories prefixed with a period.
The DIRECTORY binding lists the readable files and directories in one folder. Use it with **Listbox (Single-Select)** when the editor should pick a file, such as a logo or an mp3. The list skips only `.`, `..`, `.svn`, `.git`, and `.DS_Store`. A file such as `.htaccess` is included.

## Usage

Expand All @@ -16,19 +16,19 @@ When you create a Template Variable, place the following text into the **Input O
@DIRECTORY /path/to/some_directory
```

Frequently, this is coupled with an Input Type of "DropDown List Menu" to allow the user to select a file from the list.
Pair it with the input type **Listbox (Single-Select)** so the editor can pick one file from the list.

In MODX Revolution, the path used for the @DIRECTORY binding is relative to the site's root. It is **not** an absolute file path. If you want to list files above your site's root, you must use the ".." syntax, e.g. **@DIRECTORY /../dir\_above\_root** This binding will work with or without a trailing slash in the directory name.

If you are using the @DIRECTORY binding for your template variable `[[*myTV]]`, you can easily imagine that your template code could have some stuff in it like:
A Template can print the chosen path:

``` html
<img src="[[*myTV]]" alt="" />
```

## Additional Info

Can you filter which files are selected? E.g. using \*.jpg? The following DOES NOT WORK:
A mask such as `*.jpg` does not filter the list. This does not work:

``` php
@DIRECTORY /list/*.jpg # doesn't work!
Expand All @@ -38,7 +38,7 @@ There are PHP code snippets out there that emulate this functionality. See the f

## Security

Depending on how the file is used on the page, it may pose a security risk. Be careful if you were using this binding to select JavaScript files to be executed. What if a user had the ability to upload (and thus execute) a JavaScript file? Also, always be wary of letting users see your directory structure.
How the chosen file is used on the page can be a security risk. Do not use this binding to pick JavaScript that the page then runs: a user who can upload a file could then run it. Be wary of letting users see the directory structure.

## See Also

Expand Down
Loading
Loading