aboutsummaryrefslogtreecommitdiffhomepage
path: root/misc/render_template.php
blob: 294fc164f0596ced4ca827a010932c2a0d759ca2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
<?php

/*
here is a horrible example of php jank.
TODO: anything better than this
i'm terribly sorry for future me / anyone else who has to deal with this
*/

$__spooky_magical_template_global_state = [];

function render_template(string $templateName, array $args = []) {
    global $__spooky_magical_template_global_state;
    $__spooky_magical_template_global_state['slotParentArgs'] = $__spooky_magical_template_global_state['slotArgs'] ?? null;
    $__spooky_magical_template_global_state['slotArgs'] = $args;
    foreach ($args as $key => $value) {
        ${$key} = $value;
    }

    if (!function_exists('slot')) {
        function slot() {
            global $__spooky_magical_template_global_state;
            if (isset($__spooky_magical_template_global_state['slotParentArgs'])) {
                $parentArgs = $__spooky_magical_template_global_state['slotParentArgs'];
                foreach ($parentArgs as $key => $value) {
                    global ${$key};
                    ${$key} = $value;
                }
            }
            ($__spooky_magical_template_global_state['slotContent'] ?? function () {})();
            if (isset($parentArgs)) {
                foreach ($parentArgs as $key => $value) {
                    unset(${$key});
                }
            }
        }
        function call_template(string $templateName, array $args = [], callable $slotContent = null) {
            global $__spooky_magical_template_global_state;
            // note to self: yes this does actually clone the array
            $__spooky_magical_template_global_state['previousState'] = $__spooky_magical_template_global_state;
            $__spooky_magical_template_global_state['slotContent'] = $slotContent;
            render_template($templateName, $args);
            $__spooky_magical_template_global_state = $__spooky_magical_template_global_state['previousState'];
        }
    }

    require __DIR__ . '/../templates/' . $templateName . '.php';

    foreach ($args as $key => $value) {
        unset(${$key});
    }
}