Skip to content

Instantly share code, notes, and snippets.

@etiennemarais
Created April 11, 2016 14:06
Show Gist options
  • Save etiennemarais/7d89d8ff7d1202d68b0b166c092d6dfc to your computer and use it in GitHub Desktop.
Save etiennemarais/7d89d8ff7d1202d68b0b166c092d6dfc to your computer and use it in GitHub Desktop.
Gets all the variables from a .mustache template file with it's nested includes variables.
<?php
class Helper
{
/**
* Finds all mustache template tokens ex:
* {{> components/templates/email/includes/email-tr-spacer-thin }}
* {{# deliveryAddress }}
* {{^ deliveryAddress }}
* {{{ deliveryAddressReadable }}}
* {{ deliveryAddressReadable }}
* {{/ deliveryAddress }}
*/
const HANDLEBARS_VARIABLE_REGEX = "/[\\{]?\\{\\{(.*?)[\\}]?\\}\\}/";
/**
* @param string $mustacheTemplate
* @return array
*/
protected function getAllTemplateVariables($mustacheTemplate)
{
$templateContent = file_get_contents($this->app['view.finder']->find(trim($mustacheTemplate)));
preg_match_all(self::HANDLEBARS_VARIABLE_REGEX, $templateContent, $matches);
$templateVariables = array_map(function($variable) {
// Has included template
if ($variable[0] === '>') {
return $this->getAllTemplateVariables(str_replace('/', '.', substr($variable, 2, strlen($variable) - 2)));
}
return trim($variable);
}, $matches[1]);
return $templateVariables;
}
}
@etiennemarais
Copy link
Author

NOTE: This is for laravel so the way it finds a View is highly opinionated for Laravel 4 at this stage. This is just a little code dump for it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment