1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/** |
4
|
|
|
* @license LGPLv3, http://opensource.org/licenses/LGPL-3.0 |
5
|
|
|
* @copyright Aimeos (aimeos.org), 2017-2025 |
6
|
|
|
* @package Base |
7
|
|
|
* @subpackage View |
8
|
|
|
*/ |
9
|
|
|
|
10
|
|
|
|
11
|
|
|
namespace Aimeos\Base\View\Engine; |
12
|
|
|
|
13
|
|
|
|
14
|
|
|
/** |
15
|
|
|
* Twig view engine implementation |
16
|
|
|
* |
17
|
|
|
* @package Base |
18
|
|
|
* @subpackage View |
19
|
|
|
*/ |
20
|
|
|
class Twig implements Iface |
21
|
|
|
{ |
22
|
|
|
private $env; |
23
|
|
|
|
24
|
|
|
|
25
|
|
|
/** |
26
|
|
|
* Initializes the view object |
27
|
|
|
* |
28
|
|
|
* @param \Twig\Environment $env Twig environment object |
29
|
|
|
*/ |
30
|
|
|
public function __construct( \Twig\Environment $env ) |
31
|
|
|
{ |
32
|
|
|
$this->env = $env; |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
|
36
|
|
|
/** |
37
|
|
|
* Renders the output based on the given template file name and the key/value pairs |
38
|
|
|
* |
39
|
|
|
* @param \Aimeos\Base\View\Iface $view View object |
40
|
|
|
* @param string $filename File name of the view template |
41
|
|
|
* @param array $values Associative list of key/value pairs |
42
|
|
|
* @return string Output generated by the template |
43
|
|
|
* @throws \Aimeos\Base\View\Exception If the template isn't found |
44
|
|
|
*/ |
45
|
|
|
public function render( \Aimeos\Base\View\Iface $view, string $filename, array $values ) : string |
46
|
|
|
{ |
47
|
|
|
$loader = $this->env->getLoader(); |
48
|
|
|
|
49
|
|
|
if( ( $content = @file_get_contents( $filename ) ) === false ) { |
50
|
|
|
throw new \Aimeos\Base\View\Exception( sprintf( 'Template "%1$s" not found', $filename ) ); |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
$custom = new \Twig\Loader\ArrayLoader( array( $filename => $content ) ); |
54
|
|
|
$this->env->setLoader( new \Twig\Loader\ChainLoader( array( $custom, $loader ) ) ); |
55
|
|
|
|
56
|
|
|
try |
57
|
|
|
{ |
58
|
|
|
$template = $this->env->loadTemplate( $this->env->getTemplateClass( $filename ), $filename ); |
59
|
|
|
$content = $template->render( $values ); |
60
|
|
|
|
61
|
|
|
foreach( $template->getBlockNames( $values ) as $key ) { |
62
|
|
|
$view->block()->set( str_replace( '_', '/', $key ), $template->renderBlock( $key, $values ) ); |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
$this->env->setLoader( $loader ); |
66
|
|
|
|
67
|
|
|
return $content; |
68
|
|
|
} |
69
|
|
|
catch( \Exception $e ) |
70
|
|
|
{ |
71
|
|
|
$this->env->setLoader( $loader ); |
72
|
|
|
throw $e; |
73
|
|
|
} |
74
|
|
|
} |
75
|
|
|
} |
76
|
|
|
|