The "proper" way to develop snippets will depend on your objectives.
To set a placeholder you use the
setPlaceholder API function as explained in the wiki post:
<?php
// do some logic to get the placeholder value
$value = "MODx";
// define the placeholder and set it's value
$modx->setPlaceholder('placeholderName',$value);
?>
Then in the document you could use the [+placeholderName+], but you need to place the snippet call on the document (or in the template) in order have the placeholder set:
My favorite CMS is [+placeholderName+]!
As for the chunk, you have several options for doing this:
1) You could simply place the chunk with the placeholder in the document content and let the MODx document parser handle the placeholder.
2) You could use the
parseChunk API function to parse out the placeholders in the chunk and then output the parsed chunk:
<?php
// do some logic to get the placeholder value
$firstName = "John";
$lastName = "Smith";
// define the placeholders and set their values
$modx->setPlaceholder('firstName',$firstName);
$modx->setPlaceholder('lastName',$lastName);
// set chunk name in this example it is named addressBook
$myChunk = "addressBook";
// parse the chunk and replace the placeholder values.
// note that the values need to be in an array with the format placeholderName => placeholderValue
$values = array('firstName' => $firstName, 'lastName' => $lastName);
// run the parseChunk function
$output = $modx->parseChunk($addressBook, $values, '[+', '+]');
return $output;
?>
This will output the parsed chunk where the snippet is placed on the document.
Note: alternatively you could set the output to be a placeholder as well by removing the return statement and replacing it with a setPlaceholder function call:
<?php
//.… all the code above
$output = $modx->parseChunk($addressBook, $values, '[+', '+]');
// return $output;
$modx->setPlaceholder('output',$output);
?>
And then you would place the [+output+] placeholder where you want it to appear on the document.
3) you could use the
getChunk API function together with the
str_replace php function. This is a bit more code but can be more efficient depending on your objective. For example Ditto uses this method in a function:
<?php
// example from Ditto template.class.inc.php
// ---------------------------------------------------
// Function: replace
// Replcae placeholders with their values
// ---------------------------------------------------
function replace( $placeholders, $tpl ) {
$keys = array();
$values = array();
foreach ($placeholders as $key=>$value) {
$keys[] = '[+'.$key.'+]';
$values[] = $value;
}
return str_replace($keys,$values,$tpl);
}
?>
Hope this gets you started.