chrisdempsey
10/12/2016 - 3:59 PM

registerAssets.php

<?php
/**
 * registerAssets
 *
 * DESCRIPTION
 *
 * Registers assets to MODX Placeholder.
 * 
 * Requires call to [[activateAssets]] before closing body tag in template.  This grabs files list from the Placeholder and outputs a javascript block
 * of assets to be injected after page load.
 * 
 *
 * PROPERTIES:
 *
 * &files: string, required, path to file to register, can be external url eg. /assets/js/file.js, //netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.js
 * for multiple files separate paths with double pipes ||
 *
 * USAGE:
 *
 * [[-registerAssets?
 *      &files=`/assets/js/file1.js || /assets/css/styles.css`
 * ]]
 *
 */

if ( (!isset($modx)) || (empty($files)) ) {
    $modx->log(modX::LOG_LEVEL_ERROR, '[[registerAssets]] missing required property &files.');
    return;
}

// grab existing placeholderAssets value
$placeholderAssets = $modx->getPlaceholder('placeholderAssets');

// create array of files by splitting file_list on comma
$arr_files = explode('||', $files);

// trim any white space from file values
$arr_files = array_filter(array_map('trim', $arr_files));

// loop through array and register file by type
foreach ($arr_files as $file) {

    // set or update placeholder
    $placeholderAssets .= $file . '||';

}

// set placeholderAssets string to MODX placeholder
$modx->setPlaceholder('placeholderAssets', $placeholderAssets);

return;