src/Template/functions.php source

1 <?php
2
3 /**
4 * Template Feature - Public API Functions
5 *
6 * Provides template rendering with inheritance support.
7 */
8
9 namespace mini;
10
11 use mini\Template\RendererInterface;
12 use mini\Mini;
13 use mini\Lifetime;
14 use mini\Util\PathsRegistry;
15
16 // Register views path registry
17 $primaryViewsPath = $_ENV['MINI_VIEWS_ROOT'] ?? (Mini::$mini->root . '/_views');
18 Mini::$mini->paths->views = new PathsRegistry($primaryViewsPath);
19
20 // Add framework's _views path as fallback
21 $frameworkViewsPath = \dirname((new \ReflectionClass(Mini::class))->getFileName(), 2) . '/_views';
22 Mini::$mini->paths->views->addPath($frameworkViewsPath);
23
24 // Register Template service
25 Mini::$mini->addService(RendererInterface::class, Lifetime::Singleton, fn() => Mini::$mini->loadServiceConfig(RendererInterface::class));
26
27 /**
28 * Render a template with provided variables
29 *
30 * Supports multi-level template inheritance via $this->extend() and $this->block().
31 * Uses path registry to find templates in _views/ directory.
32 *
33 * Simple templates:
34 * ```php
35 * echo render('settings.php', ['user' => $user]);
36 * ```
37 *
38 * With layout inheritance:
39 * ```php
40 * // child.php
41 * <?php $this->extend('layout.php'); ?>
42 * <?php $this->block('title', 'My Page'); ?>
43 * <?php $this->block('content'); ?><p>Content here</p><?php $this->end(); ?>
44 *
45 * // layout.php
46 * <html><head><title><?php $this->show('title', 'Untitled'); ?></title></head>
47 * <body><?php $this->show('content'); ?></body></html>
48 * ```
49 *
50 * Including sub-templates (partials):
51 * ```php
52 * <?= mini\render('user-card.php', ['user' => $currentUser]) ?>
53 * ```
54 *
55 * @param string $template Template name/path (without extension, e.g., 'user/profile')
56 * @param array $vars Variables to make available in the template
57 * @return string Rendered template output
58 * @throws \Exception If template not found or rendering fails
59 */
60 function render(string $template, array $vars = []): string {
61 return Mini::$mini->get(RendererInterface::class)->render($template, $vars);
62 }
63
64