API:runSnippet

From MODx Wiki

Jump to: navigation, search
 API Function Definition: 
runSnippet
Versions 
> 0.9.2
Return Values
Success: Output of a given snippet
Fail: empty string (or false?)
Data Type 
string
Object Hierarchy 
DocumentParser
string runSnippet(string $snippetName [, array $params]);


Retrieves a snippet from the database (or cache) given the name of the snippet. Extra parameters may also be sent to the snippet via it's optional second parameter. This function is usually used to run a snippet from within other Snippets or even Modules.

Examples

$dittoOutput = $modx->runSnippet(
        "Ditto",
        array(
            "tpl" => "<post><title>[+title+]</title><summary>[+summary+]</summary></post>"
        )
);

Related functions

Function source

File: manager/includes/document.parser.class.inc.php
Line: 1689
  1. function runSnippet($snippetName, $params= array ()) {
  2. if (isset ($this->snippetCache[$snippetName])) {
  3. $snippet= $this->snippetCache[$snippetName];
  4. $properties= $this->snippetCache[$snippetName . "Props"];
  5. } else { // not in cache so let's check the db
  6. $sql= "SELECT * FROM " . $this->getFullTableName("site_snippets") . " WHERE " . $this->getFullTableName("site_snippets") . ".name='" . mysql_escape_string($snippetName) . "';";
  7. $result= $this->dbQuery($sql);
  8. if ($this->recordCount($result) == 1) {
  9. $row= $this->fetchRow($result);
  10. $snippet= $this->snippetCache[$row['name']]= $row['snippet'];
  11. $properties= $this->snippetCache[$row['name'] . "Props"]= $row['properties'];
  12. } else {
  13. $snippet= $this->snippetCache[$snippetName]= "return false;";
  14. $properties= '';
  15. }
  16. }
  17. // load default params/properties
  18. $parameters= $this->parseProperties($properties);
  19. $parameters= array_merge($parameters, $params);
  20. // run snippet
  21. return $this->evalSnippet($snippet, $parameters);
  22. }

Notes

The paramaters array passed to this function should be of the form 'paramater' => 'value'; If you prefer a more readable function call, create an array first, such as:

$params['param1'] = 'value1';
$params['param2'] = 'value2';
 
$html = $modx->runSnippet('mysnippet', $params);
Personal tools