-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathTemplateEngineFactory.module.php
More file actions
executable file
·399 lines (349 loc) · 12.5 KB
/
TemplateEngineFactory.module.php
File metadata and controls
executable file
·399 lines (349 loc) · 12.5 KB
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
<?php
namespace ProcessWire;
use TemplateEngineFactory\TemplateVariables;
use TemplateEngineFactory\TemplateEngineInterface;
use TemplateEngineFactory\TemplateEngineNull;
use TemplateEngineFactory\Controller;
/**
* Provides ProcessWire integration for various template engines such as Twig.
*
* @see https://github.com/wanze/TemplateEngineFactory
*/
class TemplateEngineFactory extends WireData implements Module, ConfigurableModule
{
/**
* @var array
*/
private static $defaultConfig = [
'engine' => '',
'auto_page_render' => 1,
'api_var' => 'view',
'enabled_templates' => [],
'disabled_templates' => [],
'templates_path' => 'templates/views/'
];
/**
* @var \TemplateEngineFactory\TemplateEngineInterface[]
*/
private $engines = [];
/**
* @var \ProcessWire\WireArray
*/
private $templateVariables;
public function __construct()
{
parent::__construct();
$this->templateVariables = $this->wire(new WireArray());
$this->wire('classLoader')->addNamespace('TemplateEngineFactory', __DIR__ . '/src');
$this->setDefaultConfig();
}
/**
* @return array
*/
public static function getModuleInfo()
{
return [
'title' => 'Template Engine Factory',
'version' => 210,
'author' => 'Stefan Wanzenried',
'summary' => 'Provides ProcessWire integration for various template engines such as Twig.',
'href' => 'https://processwire.com/talk/topic/6833-module-templateenginefactory/',
'singular' => true,
'autoload' => true,
'requires' => [
'PHP>=7.0',
'ProcessWire>=3.0',
],
];
}
/**
* Initialize module by hooking into Page::render.
*/
public function init()
{
if (!$this->get('auto_page_render')) {
return;
}
$this->addHookBefore('Page::render', $this, 'hookBeforePageRender');
$this->addHookAfter('Page::render', $this, 'hookAfterPageRender', ['priority' => '100.01']);
}
/**
* Register a template engine.
*
* @param string $name
* The name of the template engine, e.g. "Twig" or "Plug".
* @param \TemplateEngineFactory\TemplateEngineInterface $engine
*/
public function registerEngine($name, TemplateEngineInterface $engine)
{
$this->engines[$name] = $engine;
}
/**
* Get the current active template engine.
*
* @return \TemplateEngineFactory\TemplateEngineInterface
*/
public function getEngine()
{
$name = $this->get('engine');
return $this->engines[$name] ?? new TemplateEngineNull();
}
/**
* Render the given template and data via template engine.
*
* @param string $template
* A relative path to the template file.
* @param array $data
* Data passed to the template file.
*
* @return string
*/
public function render($template, array $data = [])
{
return $this->getEngine()->render($template, $data);
}
/**
* A controller wraps a ProcessWire template executing some logic and a template file of the active engine.
*
* @param string $controllerFile
* @param string $templateFile
*
* @return \TemplateEngineFactory\Controller
*/
public function controller($controllerFile, $templateFile)
{
return $this->wire(new Controller($this, $controllerFile, $templateFile));
}
/**
* @return \TemplateEngineFactory\TemplateEngineInterface[]
*/
public function getEngines()
{
return $this->engines;
}
/**
* Hook before rendering a page.
*
* @param \ProcessWire\HookEvent $event
*/
public function hookBeforePageRender(HookEvent $event)
{
/** @var \ProcessWire\Page $page */
$page = $event->object;
if (!$this->shouldRenderPage($page)) {
return;
}
$this->prepareTemplateVariables($page);
}
/**
* Hook after rendering a page.
*
* Replaces the return value of Page::render() with the output from
* the template engine.
*
* @param \ProcessWire\HookEvent $event
*/
public function hookAfterPageRender(HookEvent $event)
{
/** @var \ProcessWire\Page $page */
$page = $event->object;
if (!$this->shouldRenderPage($page)) {
return;
}
$template = $this->resolveTemplate($page);
$variables = $this->resolveTemplateVariables($page, $this->collectTemplateVariables());
$event->return = $this->getEngine()->render($template, $variables);
}
/**
* Get the name of the template that should be used to render the given page.
*
* By default, the module will load a template with the same name as the
* page's (ProcessWire) template name.
*
* @param \ProcessWire\Page $page
*
* @return string
*/
protected function ___resolveTemplate(Page $page)
{
return $page->get('template')->name;
}
/**
* Check if the given page should be rendered via template engine.
*
* @param \ProcessWire\Page $page
*
* @return bool
*/
protected function ___shouldRenderPage(Page $page)
{
// If the page is not viewable, there is nothing to render for the template engine.
if (!$page->viewable()) {
return false;
}
return $this->shouldRenderTemplate($page->get('template'));
}
/**
* Get variables available in the template when rendering the given page.
*
* The returned array will be passed to the engine when rendering the page.
* By default, the module includes the page being rendered as "_page".
* Note that this page might be different from the global "page" object.
*
* @param \ProcessWire\Page $page
* @param \TemplateEngineFactory\TemplateVariables $variables
*
* @return array
*/
protected function ___resolveTemplateVariables(Page $page, TemplateVariables $variables)
{
return $variables->getArray();
}
/**
* @param \ProcessWire\Template $template
*
* @return bool
*/
private function shouldRenderTemplate(Template $template)
{
// Do not render admin pages.
if ($template->name === 'admin') {
return false;
}
// Do not render pages not having a ProcessWire template file, there is no "controller" available.
if (!$template->filenameExists()) {
return false;
}
// Check if the template is enabled or disabled.
if (count($this->get('enabled_templates'))) {
return in_array($template->id, $this->get('enabled_templates'));
}
if (count($this->get('disabled_templates'))) {
return !in_array($template->id, $this->get('disabled_templates'));
}
return true;
}
/**
* Initialize new template variables when rendering the given page.
*
* @param \ProcessWire\Page $page
*
* @throws \ProcessWire\WireException
*/
private function prepareTemplateVariables(Page $page)
{
// Push any existing variables on the internal stack.
$variables = $this->wire($this->get('api_var'));
if ($variables instanceof TemplateVariables) {
$this->templateVariables->append($variables);
}
$variables = $this->wire(new TemplateVariables(['_page' => $page]));
$this->wire($this->get('api_var'), $variables);
}
/**
* Get all collected template variables after rendering a page.
*
* The ProcessWire template aka "controller" has populated these
* variables during the Page::render() call.
*
* @throws \ProcessWire\WireException
*
* @return \TemplateEngineFactory\TemplateVariables
*/
private function collectTemplateVariables()
{
$variables = $this->wire($this->get('api_var'));
// Restore previous variables from stack, in case of recursive rendering.
if ($this->templateVariables->count()) {
$this->wire($this->get('api_var'), $this->templateVariables->pop());
}
if ($variables instanceof TemplateVariables) {
return $variables;
}
return $this->wire(new TemplateVariables());
}
private function setDefaultConfig()
{
foreach (self::$defaultConfig as $key => $value) {
$this->set($key, $value);
}
}
/**
* @param array $data
*
* @throws \ProcessWire\WireException
* @throws \ProcessWire\WirePermissionException
*
* @return \ProcessWire\InputfieldWrapper
*/
public static function getModuleConfigInputfields(array $data)
{
$wrapper = new InputfieldWrapper();
$data = array_merge(self::$defaultConfig, $data);
$templates = [];
foreach (wire('templates') as $template) {
$label = $template->name;
if ($template->flags & Template::flagSystem) {
$label .= ' (system)';
}
$templates[$template->id] = $label;
}
/** @var \ProcessWire\InputfieldSelect $field */
$field = wire('modules')->get('InputfieldSelect');
$field->label = __('Template Engine');
$field->description = __('Select the template engine which is used to render the pages.');
$field->notes = __('More config options might be available in the module providing this engine.');
$field->value = $data['engine'];
$field->name = 'engine';
$engines = wire('modules')->get('TemplateEngineFactory')->getEngines();
$options = [];
foreach (array_keys($engines) as $name) {
$options[$name] = ucfirst($name);
}
$field->addOptions($options);
$wrapper->append($field);
/** @var \ProcessWire\InputfieldText $field */
$field = wire('modules')->get('InputfieldText');
$field->name = 'templates_path';
$field->label = __('Path to templates');
$field->description = __('Relative path from the site directory where template files are stored. E.g. `templates/views/` resolves to `/site/templates/views/`.');
$field->value = $data['templates_path'];
$field->required = 1;
$wrapper->append($field);
/** @var \ProcessWire\InputfieldCheckbox $field */
$field = wire('modules')->get('InputfieldCheckbox');
$field->label = __('Enable automatic page rendering');
$field->description = __('Check to delegate the rendering of pages to the template engine. You may enable or disable this behaviour for specific templates.');
$field->name = 'auto_page_render';
$field->attr('checked', (bool) $data['auto_page_render']);
$wrapper->append($field);
$field = wire('modules')->get('InputfieldText');
$field->label = __('API variable to interact with the template engine');
$field->description = __('Enter a name for the API variable used to pass data from the ProcessWire template (Controller) to the template engine.');
$field->name = 'api_var';
$field->value = $data['api_var'];
$field->required = 1;
$field->showIf = 'auto_page_render=1';
$wrapper->append($field);
$field = wire('modules')->get('InputfieldAsmSelect');
$field->label = __('Enabled templates');
$field->description = __('Restrict automatic page rendering to the templates selected here.');
$field->attr('name', 'enabled_templates');
$field->attr('value', $data['enabled_templates']);
$field->collapsed = Inputfield::collapsedBlank;
$field->showIf = 'auto_page_render=1';
$field->addOptions($templates);
$wrapper->append($field);
$field = wire('modules')->get('InputfieldAsmSelect');
$field->label = __('Disabled templates');
$field->description = __('Select templates that should **not** automatically be rendered via template engine.');
$field->notes = __('Do not use in combination with the *Enabled templates* configuration above, either enable or disable templates.');
$field->attr('name', 'disabled_templates');
$field->attr('value', $data['disabled_templates']);
$field->collapsed = Inputfield::collapsedBlank;
$field->showIf = 'auto_page_render=1';
$field->addOptions($templates);
$wrapper->append($field);
return $wrapper;
}
}