-
Notifications
You must be signed in to change notification settings - Fork 642
/
Copy pathView.php
2610 lines (2308 loc) · 87.6 KB
/
View.php
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
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* @link https://craftcms.com/
* @copyright Copyright (c) Pixel & Tonic, Inc.
* @license https://craftcms.github.io/license/
*/
namespace craft\web;
use Craft;
use craft\base\ElementInterface;
use craft\events\AssetBundleEvent;
use craft\events\CreateTwigEvent;
use craft\events\RegisterTemplateRootsEvent;
use craft\events\TemplateEvent;
use craft\helpers\App;
use craft\helpers\Cp;
use craft\helpers\FileHelper;
use craft\helpers\Html;
use craft\helpers\Json;
use craft\helpers\Path;
use craft\helpers\StringHelper;
use craft\web\twig\CpExtension;
use craft\web\twig\Environment;
use craft\web\twig\Extension;
use craft\web\twig\FeExtension;
use craft\web\twig\GlobalsExtension;
use craft\web\twig\SafeHtml;
use craft\web\twig\SinglePreloaderExtension;
use craft\web\twig\TemplateLoader;
use Illuminate\Support\Collection;
use LogicException;
use Stringable;
use Throwable;
use Twig\Error\LoaderError as TwigLoaderError;
use Twig\Error\RuntimeError as TwigRuntimeError;
use Twig\Error\SyntaxError as TwigSyntaxError;
use Twig\Extension\CoreExtension;
use Twig\Extension\ExtensionInterface;
use Twig\Extension\StringLoaderExtension;
use Twig\Runtime\EscaperRuntime;
use Twig\Template as TwigTemplate;
use Twig\TemplateWrapper;
use yii\base\Arrayable;
use yii\base\Exception;
use yii\base\Model;
use yii\base\NotSupportedException;
use yii\web\AssetBundle as YiiAssetBundle;
/**
* @inheritdoc
* @property string $templateMode the current template mode (either `site` or `cp`)
* @property string $templatesPath the base path that templates should be found in
* @property string|null $namespace the active namespace
* @property-read array $cpTemplateRoots any registered control panel template roots
* @property-read array $siteTemplateRoots any registered site template roots
* @property-read bool $isRenderingPageTemplate whether a page template is currently being rendered
* @property-read bool $isRenderingTemplate whether a template is currently being rendered
* @property-read Environment $twig the Twig environment
* @property-read string $bodyHtml the content to be inserted at the end of the body section
* @property-read string $headHtml the content to be inserted in the head section
* @property-write string[] $registeredAssetBundles the asset bundle names that should be marked as already registered
* @property-write string[] $registeredJsFiles the JS files that should be marked as already registered
* @author Pixel & Tonic, Inc. <[email protected]>
* @since 3.0.0
*/
class View extends \yii\web\View
{
/**
* @event CreateTwigEvent The event that is triggered when a Twig environment is created.
* @see createTwig()
* @since 4.3.0
*/
public const EVENT_AFTER_CREATE_TWIG = 'afterCreateTwig';
/**
* @event RegisterTemplateRootsEvent The event that is triggered when registering control panel template roots
*/
public const EVENT_REGISTER_CP_TEMPLATE_ROOTS = 'registerCpTemplateRoots';
/**
* @event RegisterTemplateRootsEvent The event that is triggered when registering site template roots
*/
public const EVENT_REGISTER_SITE_TEMPLATE_ROOTS = 'registerSiteTemplateRoots';
/**
* @event TemplateEvent The event that is triggered before a template gets rendered
*/
public const EVENT_BEFORE_RENDER_TEMPLATE = 'beforeRenderTemplate';
/**
* @event TemplateEvent The event that is triggered after a template gets rendered
*/
public const EVENT_AFTER_RENDER_TEMPLATE = 'afterRenderTemplate';
/**
* @event TemplateEvent The event that is triggered before a page template gets rendered
*/
public const EVENT_BEFORE_RENDER_PAGE_TEMPLATE = 'beforeRenderPageTemplate';
/**
* @event TemplateEvent The event that is triggered after a page template gets rendered
*/
public const EVENT_AFTER_RENDER_PAGE_TEMPLATE = 'afterRenderPageTemplate';
/**
* @event AssetBundleEvent The event that is triggered after an asset bundle is registered
* @since 4.5.0
*/
public const EVENT_AFTER_REGISTER_ASSET_BUNDLE = 'afterRegisterAssetBundle';
/**
* @const TEMPLATE_MODE_CP
*/
public const TEMPLATE_MODE_CP = 'cp';
/**
* @const TEMPLATE_MODE_SITE
*/
public const TEMPLATE_MODE_SITE = 'site';
/**
* @var bool Whether to minify CSS registered with [[registerCss()]]
* @since 3.4.0
* @deprecated in 3.6.0.
*/
public $minifyCss = false;
/**
* @var bool Whether to minify JS registered with [[registerJs()]]
* @since 3.4.0
* @deprecated in 3.6.0
*/
public $minifyJs = false;
/**
* @var bool Whether to allow [[evaluateDynamicContent()]] to be called.
*
* ::: warning
* Don’t enable this unless you have a *very* good reason to.
* :::
*
* @since 3.5.0
*/
public bool $allowEval = false;
/**
* @var Environment|null The Twig environment instance used for control panel templates
*/
private ?Environment $_cpTwig = null;
/**
* @var Environment|null The Twig environment instance used for site templates
*/
private ?Environment $_siteTwig = null;
/**
* @var array
*/
private array $_twigOptions;
/**
* @var array<class-string<ExtensionInterface>,ExtensionInterface>
* @see registerCpTwigExtension()
*/
private array $_cpTwigExtensions = [];
/**
* @var array<class-string<ExtensionInterface>,ExtensionInterface>
* @see registerSiteTwigExtension()
*/
private array $_siteTwigExtensions = [];
/**
* @var string[]
*/
private array $_templatePaths = [];
/**
* @var TemplateWrapper[]
*/
private array $_objectTemplates = [];
/**
* @var string|null
*/
private ?string $_templateMode = null;
/**
* @var array|null
*/
private ?array $_cpTemplateRoots = null;
/**
* @var array|null
*/
private ?array $_siteTemplateRoots = null;
/**
* @var array|null
*/
private ?array $_templateRoots = null;
/**
* @var string|null The root path to look for templates in
*/
private ?string $_templatesPath = null;
/**
* @var string[]
*/
private array $_defaultTemplateExtensions;
/**
* @var string[]
*/
private array $_indexTemplateFilenames;
/**
* @var string
*/
private string $_privateTemplateTrigger;
/**
* @var string|null
*/
private ?string $_namespace = null;
/**
* @var bool Whether delta input name registration is open.
* @see getIsDeltaRegistrationActive()
* @see setIsDeltaRegistrationActive()
* @see registerDeltaName()
*/
private bool $_registerDeltaNames = false;
/**
* @var string[] The registered delta input names.
* @see registerDeltaName()
*/
private array $_deltaNames = [];
/**
* @var string[] The registered modified delta input names.
* @see registerDeltaName()
*/
private array $_modifiedDeltaNames = [];
/**
* @var array The initial delta input values.
* @see setInitialDeltaValue()
*/
private array $_initialDeltaValues = [];
/**
* @var array
* @see startJsBuffer()
* @see clearJsBuffer()
*/
private array $_jsBuffers = [];
/**
* @var array
* @see startScriptBuffer()
* @see clearScriptBuffer()
*/
private array $_scriptBuffers = [];
/**
* @var array
* @see startCssBuffer()
* @see clearCssBuffer()
*/
private array $_cssBuffers = [];
/**
* @var array
* @see startCssFileBuffer()
* @see clearCssFileBuffer()
*/
private array $_cssFileBuffers = [];
/**
* @var array
* @see startJsFileBuffer()
* @see clearJsFileBuffer()
*/
private array $_jsFileBuffers = [];
/**
* @var array
* @see startHtmlBuffer()
* @see clearHtmlBuffer()
*/
private array $_htmlBuffers = [];
/**
* @var array
* @see startMetaTagBuffer()
* @see clearMetaTagBuffer()
* @since 4.5.8
*/
private array $_metaTagBuffers = [];
/**
* @var array
* @see startAssetBundleBuffer()
* @see clearAssetBundleBuffer()
*/
private array $_assetBundleBuffers = [];
/**
* @var array
* @see startJsImportBuffer()
* @see clearJsImportBuffer()
*/
private array $_jsImportBuffers = [];
/**
* @var array|null the registered generic `<script>` code blocks
* @see registerScript()
*/
private ?array $_scripts = null;
/**
* @var array the registered generic HTML code blocks
* @see registerHtml()
*/
private array $_html = [];
/**
* @var array the registered imports for JavaScript es modules
* @see registerJsImport()
*/
private array $_jsImports = [];
/**
* @var callable[][]
*/
private array $_hooks = [];
/**
* @var string|null
*/
private ?string $_renderingTemplate = null;
/**
* @var bool
*/
private bool $_isRenderingPageTemplate = false;
/**
* @var string[]
* @see registerAssetFiles()
* @see setRegisteredAssetBundles()
*/
private array $_registeredAssetBundles = [];
/**
* @var string[]
* @see registerJsFile()
* @see setRegisteredJsfiles()
*/
private array $_registeredJsFiles = [];
/**
* @inheritdoc
*/
public function init(): void
{
parent::init();
// Set the initial template mode based on whether this is a control panel or site request
$request = Craft::$app->getRequest();
if ($request->getIsConsoleRequest() || $request->getIsCpRequest()) {
$this->setTemplateMode(self::TEMPLATE_MODE_CP);
} else {
$this->setTemplateMode(self::TEMPLATE_MODE_SITE);
}
// Register the control panel hooks
$this->hook('cp.layouts.elementindex', [$this, '_prepareElementIndexVariables']);
$this->hook('cp.elements.toolbar', [$this, '_prepareElementToolbarVariables']);
$this->hook('cp.elements.sources', [$this, '_prepareElementSourcesVariables']);
$this->hook('cp.elements.element', [$this, '_elementChipHtml']);
}
/**
* Returns the Twig environment.
*
* @return Environment
*/
public function getTwig(): Environment
{
return $this->_templateMode === self::TEMPLATE_MODE_CP
? $this->_cpTwig ?? ($this->_cpTwig = $this->createTwig())
: $this->_siteTwig ?? ($this->_siteTwig = $this->createTwig());
}
/**
* Sets the Twig environment for the current template mode.
*
* @param Environment $twig
* @since 5.6.0
*/
public function setTwig(Environment $twig): void
{
if ($this->_templateMode === self::TEMPLATE_MODE_CP) {
$this->_cpTwig = $twig;
} else {
$this->_siteTwig = $twig;
}
}
/**
* Creates a new Twig environment.
*
* @return Environment
*/
public function createTwig(): Environment
{
// Log a warning if the app isn't fully initialized yet
if (!Craft::$app->getIsInitialized()) {
Craft::warning('Twig instantiated before Craft is fully initialized.', __METHOD__);
}
$twig = new Environment(new TemplateLoader($this), $this->_getTwigOptions());
// Mark SafeHtml as a safe interface
/** @var class-string<Stringable> $safeClass */
$safeClass = SafeHtml::class;
$twig->getRuntime(EscaperRuntime::class)->addSafeClass($safeClass, ['html']);
$twig->addExtension(new StringLoaderExtension());
$twig->addExtension(new Extension($this, $twig));
if ($this->_templateMode === self::TEMPLATE_MODE_CP) {
$twig->addExtension(new CpExtension());
} elseif (Craft::$app->getIsInstalled()) {
$twig->addExtension(new FeExtension());
$twig->addExtension(new GlobalsExtension());
if (Craft::$app->getConfig()->getGeneral()->preloadSingles) {
$twig->addExtension(new SinglePreloaderExtension());
}
}
// Add plugin-supplied extensions
$registeredExtensions = $this->_templateMode === self::TEMPLATE_MODE_CP
? $this->_cpTwigExtensions
: $this->_siteTwigExtensions;
foreach ($registeredExtensions as $extension) {
$twig->addExtension($extension);
}
// Set our timezone
/** @var CoreExtension $core */
$core = $twig->getExtension(CoreExtension::class);
$core->setTimezone(Craft::$app->getTimeZone());
// Fire an 'afterCreateTwig' event
if ($this->hasEventHandlers(self::EVENT_AFTER_CREATE_TWIG)) {
$this->trigger(self::EVENT_AFTER_CREATE_TWIG, new CreateTwigEvent([
'templateMode' => $this->_templateMode ?? self::TEMPLATE_MODE_SITE,
'twig' => $twig,
]));
}
return $twig;
}
/**
* Registers a new Twig extension both CP and site templates.
*
* @param ExtensionInterface $extension
*/
public function registerTwigExtension(ExtensionInterface $extension): void
{
$this->registerCpTwigExtension($extension);
$this->registerSiteTwigExtension($extension);
}
/**
* Registers a new Twig extension for CP templates.
*
* @param ExtensionInterface $extension
* @since 5.5.0
*/
public function registerCpTwigExtension(ExtensionInterface $extension): void
{
// Make sure this extension isn't already registered
$class = get_class($extension);
if (isset($this->_cpTwigExtensions[$class])) {
return;
}
$this->_cpTwigExtensions[$class] = $extension;
if (isset($this->_cpTwig)) {
try {
$this->_cpTwig->addExtension($extension);
} catch (LogicException) {
$this->_cpTwig = null;
}
}
}
/**
* Registers a new Twig extension for site templates.
*
* @param ExtensionInterface $extension
* @since 5.5.0
*/
public function registerSiteTwigExtension(ExtensionInterface $extension): void
{
// Make sure this extension isn't already registered
$class = get_class($extension);
if (isset($this->_siteTwigExtensions[$class])) {
return;
}
$this->_siteTwigExtensions[$class] = $extension;
if (isset($this->_siteTwig)) {
try {
$this->_siteTwig->addExtension($extension);
} catch (LogicException) {
$this->_siteTwig = null;
}
}
}
/**
* Returns whether a template is currently being rendered.
*
* @return bool Whether a template is currently being rendered.
*/
public function getIsRenderingTemplate(): bool
{
return isset($this->_renderingTemplate);
}
/**
* Renders a Twig template.
*
* @param string $template The name of the template to load
* @param array $variables The variables that should be available to the template
* @param string|null $templateMode The template mode to use
* @return string the rendering result
* @throws TwigLoaderError
* @throws TwigRuntimeError
* @throws TwigSyntaxError
* @throws Exception if $templateMode is invalid
*/
public function renderTemplate(string $template, array $variables = [], ?string $templateMode = null): string
{
if ($templateMode === null) {
$templateMode = $this->getTemplateMode();
}
if (!$this->beforeRenderTemplate($template, $variables, $templateMode)) {
return '';
}
Craft::debug("Rendering template: $template", __METHOD__);
$oldTemplateMode = $this->getTemplateMode();
$this->setTemplateMode($templateMode);
// Render and return
$renderingTemplate = $this->_renderingTemplate;
$this->_renderingTemplate = $template;
try {
$output = $this->getTwig()->render($template, $variables);
} finally {
$this->_renderingTemplate = $renderingTemplate;
$this->setTemplateMode($oldTemplateMode);
}
$this->afterRenderTemplate($template, $variables, $templateMode, $output);
return $output;
}
/**
* Returns whether a page template is currently being rendered.
*
* @return bool Whether a page template is currently being rendered.
*/
public function getIsRenderingPageTemplate(): bool
{
return $this->_isRenderingPageTemplate;
}
/**
* Renders a Twig template that represents an entire web page.
*
* @param string $template The name of the template to load
* @param array $variables The variables that should be available to the template
* @param string|null $templateMode The template mode to use
* @return string the rendering result
* @throws TwigLoaderError
* @throws TwigRuntimeError
* @throws TwigSyntaxError
* @throws Exception if $templateMode is invalid
*/
public function renderPageTemplate(string $template, array $variables = [], ?string $templateMode = null): string
{
if ($templateMode === null) {
$templateMode = $this->getTemplateMode();
}
if (!$this->beforeRenderPageTemplate($template, $variables, $templateMode)) {
return '';
}
ob_start();
ob_implicit_flush(false);
$oldTemplateMode = $this->getTemplateMode();
$this->setTemplateMode($templateMode);
$isRenderingPageTemplate = $this->_isRenderingPageTemplate;
$this->_isRenderingPageTemplate = true;
try {
$this->beginPage();
echo $this->renderTemplate($template, $variables);
$this->endPage();
} finally {
$this->_isRenderingPageTemplate = $isRenderingPageTemplate;
$this->setTemplateMode($oldTemplateMode);
$output = ob_get_clean();
}
$this->afterRenderPageTemplate($template, $variables, $templateMode, $output);
return $output;
}
/**
* Renders a template defined in a string.
*
* @param string $template The source template string.
* @param array $variables Any variables that should be available to the template.
* @param string $templateMode The template mode to use.
* @param bool $escapeHtml Whether dynamic HTML should be escaped
* @return string The rendered template.
* @throws TwigLoaderError
* @throws TwigSyntaxError
*/
public function renderString(string $template, array $variables = [], string $templateMode = self::TEMPLATE_MODE_SITE, bool $escapeHtml = false): string
{
// If there are no dynamic tags, just return the template
if (!str_contains($template, '{')) {
return $template;
}
$oldTemplateMode = $this->templateMode;
$this->setTemplateMode($templateMode);
$twig = $this->getTwig();
if (!$escapeHtml) {
$twig->setDefaultEscaperStrategy(false);
}
$lastRenderingTemplate = $this->_renderingTemplate;
$this->_renderingTemplate = 'string:' . $template;
try {
return $twig->createTemplate($template)->render($variables);
} finally {
$this->_renderingTemplate = $lastRenderingTemplate;
if (!$escapeHtml) {
$twig->setDefaultEscaperStrategy();
}
$this->setTemplateMode($oldTemplateMode);
}
}
/**
* Renders an object template.
*
* The passed-in `$object` will be available to the template as an `object` variable.
*
* The template will be parsed for “property tags” (e.g. `{foo}`), which will get replaced with
* full Twig output tags (e.g. `{{ object.foo|raw }}`.
*
* If `$object` is an instance of [[Arrayable]], any attributes returned by its [[Arrayable::fields()|fields()]] or
* [[Arrayable::extraFields()|extraFields()]] methods will also be available as variables to the template.
*
* @param string $template the source template string
* @param mixed $object the object that should be passed into the template
* @param array $variables any additional variables that should be available to the template
* @param string $templateMode The template mode to use.
* @return string The rendered template.
* @throws Exception in case of failure
* @throws Throwable in case of failure
*/
public function renderObjectTemplate(string $template, mixed $object, array $variables = [], string $templateMode = self::TEMPLATE_MODE_SITE): string
{
// If there are no dynamic tags, just return the template
if (!str_contains($template, '{')) {
return trim($template);
}
$oldTemplateMode = $this->templateMode;
$this->setTemplateMode($templateMode);
$twig = $this->getTwig();
// Temporarily disable strict variables if it's enabled
$strictVariables = $twig->isStrictVariables();
if ($strictVariables) {
$twig->disableStrictVariables();
}
$twig->setDefaultEscaperStrategy(false);
$lastRenderingTemplate = $this->_renderingTemplate;
$this->_renderingTemplate = 'string:' . $template;
try {
// Is this the first time we've parsed this template?
$cacheKey = md5($template);
if (!isset($this->_objectTemplates[$cacheKey])) {
// Replace shortcut "{var}"s with "{{object.var}}"s, without affecting normal Twig tags
$template = $this->normalizeObjectTemplate($template);
$this->_objectTemplates[$cacheKey] = $twig->createTemplate($template);
}
// Get the variables to pass to the template
if ($object instanceof Model) {
foreach ($object->attributes() as $name) {
if (!isset($variables[$name]) && str_contains($template, $name)) {
$variables[$name] = $object->$name;
}
}
}
if ($object instanceof Arrayable) {
// See if we should be including any of the extra fields
$extra = [];
foreach ($object->extraFields() as $field => $definition) {
if (is_int($field)) {
$field = $definition;
}
if (preg_match('/\b' . preg_quote($field, '/') . '\b/', $template)) {
$extra[] = $field;
}
}
$variables += $object->toArray([], $extra, false);
}
$variables['object'] = $object;
$variables['_variables'] = $variables;
// Render it!
/** @var TwigTemplate $templateObj */
$templateObj = $this->_objectTemplates[$cacheKey];
return trim($templateObj->render($variables));
} finally {
$this->_renderingTemplate = $lastRenderingTemplate;
$twig->setDefaultEscaperStrategy();
$this->setTemplateMode($oldTemplateMode);
// Re-enable strict variables
if ($strictVariables) {
$twig->enableStrictVariables();
}
}
}
/**
* Normalizes an object template for [[renderObjectTemplate()]].
*
* @param string $template
* @return string
*/
public function normalizeObjectTemplate(string $template): string
{
$tokens = [];
// Tokenize {% verbatim %} ... {% endverbatim %} tags in their entirety
$template = preg_replace_callback('/\{%-?\s*verbatim\s*-?%\}.*?{%-?\s*endverbatim\s*-?%\}/s',
function(array $matches) use (&$tokens) {
$token = 'tok_' . StringHelper::randomString(10);
$tokens[$token] = $matches[0];
return $token;
},
$template
);
// Tokenize any remaining Twig tags (including print tags)
$template = preg_replace_callback('/\{%-?\s*\w+.*?%\}|(?<!\{)\{\{(?!\{).+?(?<!\})\}\}(?!\})/s',
function(array $matches) use (&$tokens) {
$token = 'tok_' . StringHelper::randomString(10);
$tokens[$token] = $matches[0];
return $token;
},
$template
);
// Tokenize inline code and code blocks
$template = preg_replace_callback('/(?<!`)(`|`{3,})(?!`).*?(?<!`)\1(?!`)/s', function(array $matches) use (&$tokens) {
$token = 'tok_' . StringHelper::randomString(10);
$tokens[$token] = '{% verbatim %}' . $matches[0] . '{% endverbatim %}';
return $token;
}, $template);
// Tokenize objects (call preg_replace_callback() multiple times in case there are nested objects)
while (true) {
$template = preg_replace_callback('/\{\s*([\'"]?)\w+\1\s*:[^\{]+?\}/', function(array $matches) use (&$tokens) {
$token = 'tok_' . StringHelper::randomString(10);
$tokens[$token] = $matches[0];
return $token;
}, $template, -1, $count);
if ($count === 0) {
break;
}
}
// Swap out the remaining {xyz} tags with {{object.xyz}}
$template = preg_replace_callback('/(?<!\{)\{\s*(\w+)([^\{]*?)\}/', function(array $match) {
// Is this a function call like `clone()`?
if (!empty($match[2]) && $match[2][0] === '(') {
$replace = $match[1] . $match[2];
} else {
$replace = "(_variables.$match[1] ?? object.$match[1])$match[2]";
}
return "{{ $replace|raw }}";
}, $template);
// Bring the objects back
foreach (array_reverse($tokens) as $token => $value) {
$template = str_replace($token, $value, $template);
}
return $template;
}
/**
* Returns whether a template exists.
*
* Internally, this will just call [[resolveTemplate()]] with the given template name, and return whether that
* method found anything.
*
* @param string $name The name of the template.
* @param string|null $templateMode The template mode to use.
* @param bool $publicOnly Whether to only look for public templates (template paths that don’t start with the private template trigger).
* @return bool Whether the template exists.
* @throws Exception
*/
public function doesTemplateExist(string $name, ?string $templateMode = null, bool $publicOnly = false): bool
{
try {
return ($this->resolveTemplate($name, $templateMode, $publicOnly) !== false);
} catch (TwigLoaderError) {
// _validateTemplateName() had an issue with it
return false;
}
}
/**
* Finds a template on the file system and returns its path.
*
* All of the following files will be searched for, in this order:
*
* - TemplateName
* - TemplateName.html
* - TemplateName.twig
* - TemplateName/index.html
* - TemplateName/index.twig
*
* If this is a front-end request, the actual list of file extensions and
* index filenames are configurable via the <config5:defaultTemplateExtensions>
* and <config5:indexTemplateFilenames> config settings.
*
* For example if you set the following in config/general.php:
*
* ```php
* 'defaultTemplateExtensions' => ['htm'],
* 'indexTemplateFilenames' => ['default'],
* ```
*
* then the following files would be searched for instead:
*
* - TemplateName
* - TemplateName.htm
* - TemplateName/default.htm
*
* The actual directory that those files will depend on the current [[setTemplateMode()|template mode]]
* (probably `templates/` if it’s a front-end site request, and `vendor/craftcms/cms/src/templates/` if it’s a Control
* Panel request).
*
* If this is a front-end site request, a folder named after the current site handle will be checked first.
*
* - templates/SiteHandle/...
* - templates/...
*
* And finally, if this is a control panel request _and_ the template name includes multiple segments _and_ the first
* segment of the template name matches a plugin’s handle, then Craft will look for a template named with the
* remaining segments within that plugin’s templates/ subfolder.
*
* To put it all together, here’s where Craft would look for a template named “foo/bar”, depending on the type of
* request it is:
*
* - Front-end site requests:
* - templates/SiteHandle/foo/bar
* - templates/SiteHandle/foo/bar.html
* - templates/SiteHandle/foo/bar.twig
* - templates/SiteHandle/foo/bar/index.html
* - templates/SiteHandle/foo/bar/index.twig
* - templates/foo/bar
* - templates/foo/bar.html
* - templates/foo/bar.twig
* - templates/foo/bar/index.html
* - templates/foo/bar/index.twig
* - Control panel requests:
* - vendor/craftcms/cms/src/templates/foo/bar
* - vendor/craftcms/cms/src/templates/foo/bar.html
* - vendor/craftcms/cms/src/templates/foo/bar.twig
* - vendor/craftcms/cms/src/templates/foo/bar/index.html
* - vendor/craftcms/cms/src/templates/foo/bar/index.twig
* - path/to/fooplugin/templates/bar
* - path/to/fooplugin/templates/bar.html
* - path/to/fooplugin/templates/bar.twig
* - path/to/fooplugin/templates/bar/index.html
* - path/to/fooplugin/templates/bar/index.twig
*
* @param string $name The name of the template.
* @param string|null $templateMode The template mode to use.
* @param bool $publicOnly Whether to only look for public templates (template paths that don’t start with the private template trigger).
* @return string|false The path to the template if it exists, or `false`.
* @throws TwigLoaderError
*/
public function resolveTemplate(string $name, ?string $templateMode = null, bool $publicOnly = false): string|false
{
if ($templateMode !== null) {
$oldTemplateMode = $this->getTemplateMode();
$this->setTemplateMode($templateMode);
}
try {
return $this->_resolveTemplateInternal($name, $publicOnly);
} finally {
if (isset($oldTemplateMode)) {
$this->setTemplateMode($oldTemplateMode);
}
}
}
/**
* Finds a template on the file system and returns its path.
*
* @param string $name The name of the template.
* @param bool $publicOnly Whether to only look for public templates (template paths that don’t start with the private template trigger).
* @return string|false The path to the template if it exists, or `false`.
* @throws TwigLoaderError
*/
private function _resolveTemplateInternal(string $name, bool $publicOnly): string|false
{
// Normalize the template name
$name = trim(preg_replace('#/{2,}#', '/', str_replace('\\', '/', StringHelper::convertToUtf8($name))), '/');
$key = $this->_templatesPath . ':' . $name;
// Is this template path already cached?
if (isset($this->_templatePaths[$key])) {
return $this->_templatePaths[$key];
}
// Validate the template name
$this->_validateTemplateName($name);
// Look for the template in the main templates folder
$basePaths = [];
// Should we be looking for a localized version of the template?
if ($this->_templateMode === self::TEMPLATE_MODE_SITE && Craft::$app->getIsInstalled()) {
/** @noinspection PhpUnhandledExceptionInspection */
$sitePath = $this->_templatesPath . DIRECTORY_SEPARATOR . Craft::$app->getSites()->getCurrentSite()->handle;
if (is_dir($sitePath)) {
$basePaths[] = $sitePath;
}
}
$basePaths[] = $this->_templatesPath;
foreach ($basePaths as $basePath) {
if (($path = $this->_resolveTemplate($basePath, $name, $publicOnly)) !== null) {
return $this->_templatePaths[$key] = $path;
}
}
unset($basePaths);
// Check any registered template roots
if ($this->_templateMode === self::TEMPLATE_MODE_CP) {
$roots = $this->getCpTemplateRoots();
} else {
$roots = $this->getSiteTemplateRoots();