Skip to content

Instantly share code, notes, and snippets.

@lyrixx
Last active November 9, 2023 13:51
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lyrixx/dd0249ef9f21a4fa63c5abe3929a68ac to your computer and use it in GitHub Desktop.
Save lyrixx/dd0249ef9f21a4fa63c5abe3929a68ac to your computer and use it in GitHub Desktop.
Updated your templates with the new twig include
<?php
<<<CONFIG
packages:
- "symfony/finder: ~3.0"
- "symfony/console: ~3.0"
CONFIG;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Finder\Finder;
(new Application('Twig replace include', '1.0'))
->register('run')
->addArgument('path', InputArgument::REQUIRED, 'The folder where are located the templates.')
->setCode(function (InputInterface $input, OutputInterface $output) {
$finder = Finder::create()
->in($input->getArgument('path'))
->files()
;
foreach ($finder as $filename) {
$content = file_get_contents($filename);
if (false === strpos($content, 'include')) {
continue;
}
$callback = function(array $matches) {
$layout = '{{ include(\'%s\'%s%s) }}';
$templateName = $matches['templateName'];
$templateName = str_replace(':', '/', $templateName);
$templateName = ltrim($templateName, '/');
$variables = $only = '';
if (isset($matches['variables'])) {
$variables = ', {'.$matches['variables'].'}';
}
if (isset($matches['only'])) {
$only = ', with_context = false';
}
return sprintf($layout, $templateName, $variables, $only);
};
$pattern = '#{%[\s\\n]+include[\s\\n]+\'(?<templateName>[\w+\.-_]+)\'(?:[\s\\n]+with[\s\\n]+{(?<variables>(?:.|\n)*)})?(?:[\s\\n]+(?<only>only)[\s\\n]+)?[\s\\n]*%}#U';
$content = preg_replace_callback($pattern, $callback, $content);
file_put_contents($filename, $content);
}
})
->getApplication()
->setDefaultCommand('run', true)
->run()
;
@lyrixx
Copy link
Author

lyrixx commented Sep 27, 2017

Usage: melody run https://gist.github.com/lyrixx/dd0249ef9f21a4fa63c5abe3929a68ac app/Resources/views/

For more information about melody, see the official website

@stof
Copy link

stof commented Dec 20, 2018

this is missing support for the whitespace-controll on the include tag

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