Skip to content

Commit

Permalink
Improve Twig support
Browse files Browse the repository at this point in the history
  • Loading branch information
ausi committed Mar 16, 2023
1 parent c8ccfa6 commit 12082f0
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 0 deletions.
20 changes: 20 additions & 0 deletions src/CustomElements.php
Original file line number Diff line number Diff line change
Expand Up @@ -1170,6 +1170,16 @@ public static function getConfigByType($type)
$configPath = null;
}

if ($configPath === null) {
try {
$twigLoader = System::getContainer()->get('contao.twig.filesystem_loader');
$configPath = substr($twigLoader->getSourceContext($twigLoader->getFirst($type))->getPath(), 0, -10) . '_config.php';
}
catch (\Exception $e) {
$configPath = null;
}
}

if ($configPath === null || !file_exists($configPath)) {
$allConfigs = array_merge(
glob(System::getContainer()->getParameter('kernel.project_dir') . '/templates/' . $type . '_config.php') ?: array(),
Expand Down Expand Up @@ -1430,6 +1440,7 @@ function ($count) {
}
}

$twigLoader = System::getContainer()->get('contao.twig.filesystem_loader');
$saveToCache = true;
$elements = array();

Expand All @@ -1451,6 +1462,15 @@ function ($count) {
$configPath = null;
}

if ($configPath === null) {
try {
$configPath = substr($twigLoader->getSourceContext($twigLoader->getFirst($template))->getPath(), 0, -10) . '_config.php';
}
catch (\Exception $e) {
$configPath = null;
}
}

if ($configPath === null || !file_exists($configPath)) {
if (isset($fallbackConfigPaths[$template])) {
$configPath = $fallbackConfigPaths[$template];
Expand Down
25 changes: 25 additions & 0 deletions src/Template/CustomTemplate.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
use Contao\FrontendTemplate;
use Contao\System;
use Contao\ThemeModel;
use Symfony\Component\Filesystem\Path;

/**
* Custom backend template
Expand Down Expand Up @@ -89,4 +90,28 @@ public static function getTemplates($template, $format = 'html5')

return array(parent::getTemplate($template, $format));
}

protected function renderTwigSurrogateIfExists(): ?string
{
$backupTemplate = $this->strTemplate;
$templatesDir = Path::join(System::getContainer()->getParameter('kernel.project_dir'), 'templates');

try {
$themeTemplate = static::getTemplate($this->strTemplate, 'html.twig');

if ($themeTemplate && Path::isBasePath($templatesDir, $themeTemplate)) {
$this->strTemplate = substr(Path::makeRelative($themeTemplate, $templatesDir), 0, -10);
}
}
catch (\Throwable $e) {
// Ignore
}

try {
return parent::renderTwigSurrogateIfExists();
}
finally {
$this->strTemplate = $backupTemplate;
}
}
}

0 comments on commit 12082f0

Please sign in to comment.