-
-
Notifications
You must be signed in to change notification settings - Fork 112
Description
Currently Latte does only provide a FileLoader which allows to bind templates to a single directory.
I think it would be great if Latte would provide additional Loader which allows to register multiple directories via a namespace. So Latte could example use in Laminas Framework as Renderer also by multiple Modules which could registering additional paths.
In twig example the loader accepts multiple paths and the loader will then look one after the other directory.
Another possibility in twig is a namespace example I can have @app/test.html.twig and @other/test.html.twig and register paths like:
[
'app' => __DIR__ . '/templates',
'other' => __DIR__ . '/vendor/other/module/templates',
]While in twig the @ symbol is used, I found while working on my abstraction that other frameworks use the :: syntax for this e.g. other::blade.
A implementation could look like the following:
MultiPathLoader.php
<?php
/**
* This file is part of the Latte (https://latte.nette.org)
* Copyright (c) 2008 David Grudl (https://davidgrudl.com)
*/
declare(strict_types=1);
namespace Latte\Loaders;
use Latte;
/**
* Template loader.
*/
class MultiPathLoader implements Latte\Loader
{
private array $loaders = [];
public function __construct(?array $baseDirs = ['' => null])
{
foreach ($baseDirs as $key => $baseDir) {
$this->loaders[$key] = new FileLoader($baseDir);
}
}
/**
* Returns template source code.
*/
public function getContent(string $name): string
{
[$loader, $name] = $this->extractLoaderAndName($name);
return $loader->isExpired($name, $name);
}
public function isExpired(string $file, int $time): bool
{
[$loader, $name] = $this->extractLoaderAndName($file);
return $loader->isExpired($name, $time);
}
/**
* Returns referred template name.
*/
public function getReferredName(string $name, string $referringName): string
{
[$loader, $name] = $this->extractLoaderAndName($name);
return $loader->getReferredName($name, $referringName);
}
/**
* Returns unique identifier for caching.
*/
public function getUniqueId(string $name): string
{
[$loader, $name] = $this->extractLoaderAndName($name);
return $loader->getUniqueId($name);
}
private function extractLoaderAndName(string $name): array
{
if (\str_starts_with('@', $name)) {
// the `@module/template` syntax
[$loaderKey, $fileName] = \explode('/', substr($name, 1), 2);
// alternative `module::template` syntax
[$loaderKey, $fileName] = \explode('::', $name, 2);
return [
$this->loaders[$loaderKey],
$fileName,
];
}
return [
$this->loaders[''],
$name,
];
}
}What do you think about this. Is this a Loader which you think make sense to live inside Latte Core and you are open for a pull request for it?