Skip to content

Instantly share code, notes, and snippets.

@laras126
Created December 9, 2018 22:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save laras126/f15181ade695d00b4e57c7e2f0e356c1 to your computer and use it in GitHub Desktop.
Save laras126/f15181ade695d00b4e57c7e2f0e356c1 to your computer and use it in GitHub Desktop.
Possible way to generate PHP from template syntax
<?php
function render_component( $component, $data ) {
// Should be replaced with node_modules path.
$twig_file = CHILD_THEME_PATH . '/assets/src/modules/' . $component . '/' . $component . '.twig';
$template_path = CHILD_THEME_PATH . '/template-parts/pmc-components/' . $component . '.php';
if ( file_exists( $twig_file ) && 0 === validate_file( $twig_file ) ) {
$twig_markup = PMC::render_template( $twig_file, [] );
// Get matches for {{ name }}
// https://regex101.com/r/ACN0rE/1
$full_pattern = '/({{\s*)(\w*)(\s*}})/';
preg_match_all( $full_pattern, $twig_markup, $matches );
$count = 0;
$replacements = [];
foreach ( $matches[0] as $key => $match ) {
$variable_name = $matches[2][$count];
$is_class = strpos( $match, 'class');
$is_url = strpos( $match, 'url');
if ( ! empty( $is_url ) ) {
$replacements[$count] = '<?php echo esc_url( $' . $variable_name . ' ); ?>';
}
if ( ! empty( $is_class ) ) {
$replacements[$count] = '<?php echo esc_attr( $' . $variable_name . ' ); ?>';
}
$count++;
}
$php_markup = "<?php\n// This is a generated file. Refer to the file located at $twig_file for adjusting this markup.\n?>\n";
$php_markup .= str_replace( $matches[0], $replacements, $twig_markup );
$handle = fopen( $template_path, 'w' );
fwrite( $handle, $php_markup );
} else {
echo 'no file here huh';
}
PMC::render_template( $template_path, $data, true );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment