Created
December 9, 2018 22:57
-
-
Save laras126/f15181ade695d00b4e57c7e2f0e356c1 to your computer and use it in GitHub Desktop.
Possible way to generate PHP from template syntax
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
<?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