Last active
April 22, 2017 16:14
-
-
Save paullinney/a63658ec77db24cfefc45253b9c0d64e to your computer and use it in GitHub Desktop.
Drupal 7 module funcitons for including angular app into page/block
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Page for application. | |
*/ | |
function MYMODULE_application_page_callback() { | |
global $user; | |
drupal_add_html_head([ | |
'#tag' => 'base', | |
'#attributes' => array( | |
'href' => '/MYMODULE_PATH', | |
), | |
], | |
list($assets_js, $assets_css) = MYMODULE_get_application_assets(); | |
return [ | |
'#theme' => 'MYMODULE_MYAPP', | |
'#data' => [ | |
'uuid' => $user->uuid, // Required if requesting/posting back data | |
'csrf' => drupal_get_token('services'), // Required if requesting/posting back data | |
'js' => $assets_js, | |
'css' => $assets_css | |
], | |
]; | |
} | |
/** | |
* Implements hook_theme(). | |
*/ | |
function MYMODULE_theme() { | |
// @see https://gist.github.com/paullinney/55a9f6052229432e645bc63c269aa950 | |
return array( | |
'MYMODULE_MYAPP' => array( | |
'render_element' => 'element', | |
'variables' => array('data' => NULL), | |
'template' => 'templates/MYMODULE_MYAPP', | |
), | |
); | |
} | |
/** | |
* Scan app dist folder and return webpack bundles in correct order. | |
*/ | |
function MYMODULE_get_application_assets() { | |
$application_dist_path = '/app/dist'; | |
$path = drupal_get_path('module', 'MYMODULE') . $application_dist_path; | |
$files = file_scan_directory(dirname(__DIR__) . $application_dist_path, '/(js|css)$/', ['recurse' => FALSE]); | |
$assets_js = $assets_css = []; | |
$asset_order = [ | |
'inline', | |
'polyfills', | |
'scripts', | |
'vendor', | |
'main', | |
'styles' | |
]; | |
foreach ($asset_order as $asset) { | |
if (preg_match('/^styles$/', $asset)) { | |
$assets_css[] = $path . '/' . MYMODULE_application_assets_ordering($asset, $files); | |
} | |
else { | |
$assets_js[] = $path . '/' . MYMODULE_application_assets_ordering($asset, $files); | |
} | |
} | |
return [$assets_js, $assets_css]; | |
} | |
function MYMODULE_application_assets_ordering($asset, $files){ | |
foreach ($files as $file) { | |
if (preg_match('/^(' . $asset . ')\.(.*)\.bundle\.(js|css)$/', $file->filename)) { | |
return $file->filename; | |
break; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment