-
Notifications
You must be signed in to change notification settings - Fork 642
/
Copy pathView.php
1833 lines (1584 loc) · 59.9 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\Element;
use craft\events\RegisterTemplateRootsEvent;
use craft\events\TemplateEvent;
use craft\helpers\ElementHelper;
use craft\helpers\FileHelper;
use craft\helpers\Html as HtmlHelper;
use craft\helpers\Json;
use craft\helpers\Path;
use craft\helpers\StringHelper;
use craft\helpers\UrlHelper;
use craft\web\twig\Environment;
use craft\web\twig\Extension;
use craft\web\twig\Template;
use craft\web\twig\TemplateLoader;
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\DebugExtension;
use Twig\Extension\ExtensionInterface;
use Twig\Extension\StringLoaderExtension;
use Twig\Template as TwigTemplate;
use yii\base\Arrayable;
use yii\base\Exception;
use yii\base\Model;
use yii\helpers\Html;
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 CP 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
*/
class View extends \yii\web\View
{
// Constants
// =========================================================================
/**
* @event RegisterTemplateRootsEvent The event that is triggered when registering CP template roots
*/
const EVENT_REGISTER_CP_TEMPLATE_ROOTS = 'registerCpTemplateRoots';
/**
* @event RegisterTemplateRootsEvent The event that is triggered when registering site template roots
*/
const EVENT_REGISTER_SITE_TEMPLATE_ROOTS = 'registerSiteTemplateRoots';
/**
* @event TemplateEvent The event that is triggered before a template gets rendered
*/
const EVENT_BEFORE_RENDER_TEMPLATE = 'beforeRenderTemplate';
/**
* @event TemplateEvent The event that is triggered after a template gets rendered
*/
const EVENT_AFTER_RENDER_TEMPLATE = 'afterRenderTemplate';
/**
* @event TemplateEvent The event that is triggered before a page template gets rendered
*/
const EVENT_BEFORE_RENDER_PAGE_TEMPLATE = 'beforeRenderPageTemplate';
/**
* @event TemplateEvent The event that is triggered after a page template gets rendered
*/
const EVENT_AFTER_RENDER_PAGE_TEMPLATE = 'afterRenderPageTemplate';
/**
* @const TEMPLATE_MODE_CP
*/
const TEMPLATE_MODE_CP = 'cp';
/**
* @const TEMPLATE_MODE_SITE
*/
const TEMPLATE_MODE_SITE = 'site';
// Properties
// =========================================================================
/**
* @var array The sizes that element thumbnails should be rendered in
*/
private static $_elementThumbSizes = [30, 60, 100, 200];
/**
* @var Environment|null The Twig environment instance used for CP templates
*/
private $_cpTwig;
/**
* @var Environment|null The Twig environment instance used for site templates
*/
private $_siteTwig;
/**
* @var
*/
private $_twigOptions;
/**
* @var ExtensionInterface[] List of Twig extensions registered with [[registerTwigExtension()]]
*/
private $_twigExtensions = [];
/**
* @var
*/
private $_templatePaths;
/**
* @var
*/
private $_objectTemplates;
/**
* @var string|null
*/
private $_templateMode;
/**
* @var array|null
*/
private $_cpTemplateRoots;
/**
* @var array|null
*/
private $_siteTemplateRoots;
/**
* @var array|null
*/
private $_templateRoots;
/**
* @var string|null The root path to look for templates in
*/
private $_templatesPath;
/**
* @var
*/
private $_defaultTemplateExtensions;
/**
* @var
*/
private $_indexTemplateFilenames;
/**
* @var
*/
private $_namespace;
/**
* @var array
*/
private $_jsBuffers = [];
/**
* @var array the registered generic `<script>` code blocks
* @see registerScript()
*/
private $_scripts;
/**
* @var
*/
private $_hooks;
/**
* @var
*/
private $_textareaMarkers;
/**
* @var
*/
private $_renderingTemplate;
/**
* @var
*/
private $_isRenderingPageTemplate = false;
/**
* @var string[]
* @see registerAssetFiles()
* @see setRegisteredAssetBundles()
*/
private $_registeredAssetBundles = [];
/**
* @var string[]
* @see registerJsFile()
* @see setRegisteredJsfiles()
*/
private $_registeredJsFiles = [];
// Public Methods
// =========================================================================
/**
* @inheritdoc
*/
public function init()
{
parent::init();
// Set the initial template mode based on whether this is a CP 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 cp.elements.element hook
$this->hook('cp.elements.element', [$this, '_getCpElementHtml']);
}
/**
* 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());
}
/**
* Creates a new Twig environment.
*
* @return Environment
*/
public function createTwig(): Environment
{
$twig = new Environment(new TemplateLoader($this), $this->_getTwigOptions());
$twig->addExtension(new StringLoaderExtension());
$twig->addExtension(new Extension($this, $twig));
if (YII_DEBUG) {
$twig->addExtension(new DebugExtension());
}
// Add plugin-supplied extensions
foreach ($this->_twigExtensions as $extension) {
$twig->addExtension($extension);
}
// Set our timezone
/** @var CoreExtension $core */
$core = $twig->getExtension(CoreExtension::class);
$core->setTimezone(Craft::$app->getTimeZone());
return $twig;
}
/**
* Registers a new Twig extension, which will be added on existing environments and queued up for future environments.
*
* @param ExtensionInterface $extension
*/
public function registerTwigExtension(ExtensionInterface $extension)
{
// Make sure this extension isn't already registered
$class = get_class($extension);
if (isset($this->_twigExtensions[$class])) {
return;
}
$this->_twigExtensions[$class] = $extension;
// Add it to any existing Twig environments
if ($this->_cpTwig !== null) {
$this->_cpTwig->addExtension($extension);
}
if ($this->_siteTwig !== null) {
$this->_siteTwig->addExtension($extension);
}
}
/**
* Returns whether a template is currently being rendered.
*
* @return bool Whether a template is currently being rendered.
*/
public function getIsRenderingTemplate(): bool
{
return $this->_renderingTemplate !== null;
}
/**
* 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
* @return string the rendering result
* @throws TwigLoaderError
* @throws TwigRuntimeError
* @throws TwigSyntaxError
*/
public function renderTemplate(string $template, array $variables = []): string
{
if (!$this->beforeRenderTemplate($template, $variables)) {
return '';
}
Craft::debug("Rendering template: $template", __METHOD__);
// Render and return
$renderingTemplate = $this->_renderingTemplate;
$this->_renderingTemplate = $template;
try {
$output = $this->getTwig()->render($template, $variables);
} catch (\RuntimeException $e) {
if (!YII_DEBUG) {
// Throw a generic exception instead
throw new \RuntimeException('An error occurred when rendering a template.', 0, $e);
}
throw $e;
}
$this->_renderingTemplate = $renderingTemplate;
$this->afterRenderTemplate($template, $variables, $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
* @return string the rendering result
* @throws TwigLoaderError
* @throws TwigRuntimeError
* @throws TwigSyntaxError
*/
public function renderPageTemplate(string $template, array $variables = []): string
{
if (!$this->beforeRenderPageTemplate($template, $variables)) {
return '';
}
ob_start();
ob_implicit_flush(false);
$isRenderingPageTemplate = $this->_isRenderingPageTemplate;
$this->_isRenderingPageTemplate = true;
$this->beginPage();
echo $this->renderTemplate($template, $variables);
$this->endPage();
$this->_isRenderingPageTemplate = $isRenderingPageTemplate;
$output = ob_get_clean();
$this->afterRenderPageTemplate($template, $variables, $output);
return $output;
}
/**
* Renders a macro within a given Twig template.
*
* @param string $template The name of the template the macro lives in.
* @param string $macro The name of the macro.
* @param array $args Any arguments that should be passed to the macro.
* @return string The rendered macro output.
* @throws TwigLoaderError
* @throws TwigRuntimeError
* @throws TwigSyntaxError
*/
public function renderTemplateMacro(string $template, string $macro, array $args = []): string
{
$twig = $this->getTwig();
$twigTemplate = $twig->loadTemplate($template);
$renderingTemplate = $this->_renderingTemplate;
$this->_renderingTemplate = $template;
try {
$output = call_user_func_array([$twigTemplate, 'macro_' . $macro], $args);
} catch (\RuntimeException $e) {
if (!YII_DEBUG) {
// Throw a generic exception instead
throw new \RuntimeException('An error occurred when rendering a template.', 0, $e);
}
throw $e;
}
$this->_renderingTemplate = $renderingTemplate;
return (string)$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.
* @return string The rendered template.
* @throws TwigLoaderError
* @throws TwigSyntaxError
*/
public function renderString(string $template, array $variables = []): string
{
// If there are no dynamic tags, just return the template
if (strpos($template, '{') === false) {
return $template;
}
$templateMode = $this->templateMode;
$this->setTemplateMode(self::TEMPLATE_MODE_SITE);
$twig = $this->getTwig();
$twig->setDefaultEscaperStrategy(false);
$lastRenderingTemplate = $this->_renderingTemplate;
$this->_renderingTemplate = 'string:' . $template;
$e = null;
try {
$result = $twig->createTemplate($template)->render($variables);
} catch (\Throwable $e) {
// throw it later
}
$this->_renderingTemplate = $lastRenderingTemplate;
$twig->setDefaultEscaperStrategy();
$this->setTemplateMode($templateMode);
if ($e !== null) {
if (!YII_DEBUG) {
// Throw a generic exception instead
throw new Exception('An error occurred when rendering a template.', 0, $e);
}
throw $e;
}
return $result;
}
/**
* 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
* @return string The rendered template.
* @throws Exception in case of failure
* @throws \Throwable in case of failure
*/
public function renderObjectTemplate(string $template, $object, array $variables = []): string
{
// If there are no dynamic tags, just return the template
if (strpos($template, '{') === false) {
return $template;
}
$templateMode = $this->templateMode;
$this->setTemplateMode(self::TEMPLATE_MODE_SITE);
$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;
$e = null;
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]) && strpos($template, $name) !== false) {
$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 (strpos($template, $field) !== false) {
$extra[] = $field;
}
}
$variables = array_merge($object->toArray([], $extra, false), $variables);
}
$variables['object'] = $object;
$variables['_variables'] = $variables;
// Render it!
/** @var TwigTemplate $templateObj */
$templateObj = $this->_objectTemplates[$cacheKey];
$output = $templateObj->render($variables);
} catch (\Throwable $e) {
// throw it later
}
$this->_renderingTemplate = $lastRenderingTemplate;
$twig->setDefaultEscaperStrategy();
$this->setTemplateMode($templateMode);
// Re-enable strict variables
if ($strictVariables) {
$twig->enableStrictVariables();
}
if ($e !== null) {
if (!YII_DEBUG) {
// Throw a generic exception instead
throw new Exception('An error occurred when rendering a template.', 0, $e);
}
throw $e;
}
return $output;
}
/**
* Normalizes an object template for [[renderObjectTemplate()]].
*
* @param string $template
* @return string
*/
public function normalizeObjectTemplate(string $template): string
{
// Tokenize objects (call preg_replace_callback() multiple times in case there are nested objects)
$tokens = [];
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('/(?<!\{)\{\s*(\w+)([^\{]*?)\}/', '{{ (_variables.$1 ?? object.$1)$2|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.
* @return bool Whether the template exists.
*/
public function doesTemplateExist(string $name): bool
{
try {
return ($this->resolveTemplate($name) !== false);
} catch (TwigLoaderError $e) {
// _validateTemplateName() han 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
* [[\craft\config\GeneralConfig::defaultTemplateExtensions|defaultTemplateExtensions]] and
* [[\craft\config\GeneralConfig::indexTemplateFilenames|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.
* @return string|false The path to the template if it exists, or `false`.
*/
public function resolveTemplate(string $name)
{
// 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)) !== 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();
}
if (!empty($roots)) {
foreach ($roots as $templateRoot => $basePaths) {
/** @var string[] $basePaths */
$templateRootLen = strlen($templateRoot);
if (strncasecmp($templateRoot . '/', $name . '/', $templateRootLen + 1) === 0) {
$subName = strlen($name) === $templateRootLen ? '' : substr($name, $templateRootLen + 1);
foreach ($basePaths as $basePath) {
if (($path = $this->_resolveTemplate($basePath, $subName)) !== null) {
return $this->_templatePaths[$key] = $path;
}
}
}
}
}
return false;
}
/**
* Returns any registered CP template roots.
*
* @return array
*/
public function getCpTemplateRoots(): array
{
return $this->_getTemplateRoots('cp');
}
/**
* Returns any registered site template roots.
*
* @return array
*/
public function getSiteTemplateRoots(): array
{
return $this->_getTemplateRoots('site');
}
/**
* Registers a hi-res CSS code block.
*
* @param string $css the CSS code block to be registered
* @param array $options the HTML attributes for the style tag.
* @param string|null $key the key that identifies the CSS code block. If null, it will use
* $css as the key. If two CSS code blocks are registered with the same key, the latter
* will overwrite the former.
* @deprecated in 3.0. Use [[registerCss()]] and type your own media selector.
*/
public function registerHiResCss(string $css, array $options = [], string $key = null)
{
Craft::$app->getDeprecator()->log('registerHiResCss', 'craft\\web\\View::registerHiResCss() has been deprecated. Use registerCss() instead, and type your own media selector.');
$css = "@media only screen and (-webkit-min-device-pixel-ratio: 1.5),\n" .
"only screen and ( -moz-min-device-pixel-ratio: 1.5),\n" .
"only screen and ( -o-min-device-pixel-ratio: 3/2),\n" .
"only screen and ( min-device-pixel-ratio: 1.5),\n" .
"only screen and ( min-resolution: 1.5dppx){\n" .
$css . "\n" .
'}';
$this->registerCss($css, $options, $key);
}
/**
* @inheritdoc
*/
public function registerJs($js, $position = self::POS_READY, $key = null)
{
// Trim any whitespace and ensure it ends with a semicolon.
$js = StringHelper::ensureRight(trim($js, " \t\n\r\0\x0B"), ';');
parent::registerJs($js, $position, $key);
}
/**
* Starts a JavaScript buffer.
*
* JavaScript buffers work similarly to [output buffers](http://php.net/manual/en/intro.outcontrol.php) in PHP.
* Once you’ve started a JavaScript buffer, any JavaScript code included with [[registerJs()]] will be included
* in a buffer, and you will have the opportunity to fetch all of that code via [[clearJsBuffer()]] without
* having it actually get output to the page.
*/
public function startJsBuffer()
{
// Save any currently queued JS into a new buffer, and reset the active JS queue
$this->_jsBuffers[] = $this->js;
$this->js = [];
}
/**
* Clears and ends a JavaScript buffer, returning whatever JavaScript code was included while the buffer was active.
*
* @param bool $scriptTag Whether the JavaScript code should be wrapped in a `<script>` tag. Defaults to `true`.
* @return string|false The JS code that was included in the active JS buffer, or `false` if there isn’t one
*/
public function clearJsBuffer(bool $scriptTag = true)
{
if (empty($this->_jsBuffers)) {
return false;
}
// Combine the JS
$js = '';
foreach ([self::POS_HEAD, self::POS_BEGIN, self::POS_END, self::POS_LOAD, self::POS_READY] as $pos) {
if (!empty($this->js[$pos])) {
$js .= implode("\n", $this->js[$pos]) . "\n";
}
}
// Set the active queue to the last one
$this->js = array_pop($this->_jsBuffers);
if ($scriptTag === true && !empty($js)) {
return Html::script($js, ['type' => 'text/javascript']);
}
return $js;
}
/**
* @inheritdoc
*/
public function registerJsFile($url, $options = [], $key = null)
{
// If 'depends' is specified, ignore it for now because the file will
// get registered as an asset bundle
if (empty($options['depends'])) {
$key = $key ?: $url;
if (isset($this->_registeredJsFiles[$key])) {
return;
}
$this->_registeredJsFiles[$key] = true;
}
parent::registerJsFile($url, $options, $key);
}
/**
* Registers a generic `<script>` code block.
*
* @param string $script the generic `<script>` code block to be registered
* @param int $position the position at which the generic `<script>` code block should be inserted
* in a page. The possible values are:
* - [[POS_HEAD]]: in the head section
* - [[POS_BEGIN]]: at the beginning of the body section
* - [[POS_END]]: at the end of the body section
* @param array $options the HTML attributes for the `<script>` tag.
* @param string $key the key that identifies the generic `<script>` code block. If null, it will use
* $script as the key. If two generic `<script>` code blocks are registered with the same key, the latter
* will overwrite the former.
*/
public function registerScript($script, $position = self::POS_END, $options = [], $key = null)
{
$key = $key ?: md5($script);
$this->_scripts[$position][$key] = Html::script($script, $options);
}
/**
* @inheritdoc
*/
public function endBody()
{
$this->registerAssetFlashes();
parent::endBody();
}
/**
* Returns the content to be inserted in the head section.
*
* This includes:
* - Meta tags registered using [[registerMetaTag()]]
* - Link tags registered with [[registerLinkTag()]]
* - CSS code registered with [[registerCss()]]
* - CSS files registered with [[registerCssFile()]]
* - JS code registered with [[registerJs()]] with the position set to [[POS_HEAD]]
* - JS files registered with [[registerJsFile()]] with the position set to [[POS_HEAD]]
*
* @param bool $clear Whether the content should be cleared from the queue (default is true)
* @return string the rendered content
*/
public function getHeadHtml(bool $clear = true): string
{
// Register any asset bundles
$this->registerAllAssetFiles();
$html = $this->renderHeadHtml();
if ($clear === true) {
$this->metaTags = [];
$this->linkTags = [];
$this->css = [];
$this->cssFiles = [];
unset($this->jsFiles[self::POS_HEAD], $this->js[self::POS_HEAD]);
}
return $html;
}
/**
* Returns the content to be inserted at the end of the body section.
*
* This includes:
* - JS code registered with [[registerJs()]] with the position set to [[POS_BEGIN]], [[POS_END]], [[POS_READY]], or [[POS_LOAD]]
* - JS files registered with [[registerJsFile()]] with the position set to [[POS_BEGIN]] or [[POS_END]]
*
* @param bool $clear Whether the content should be cleared from the queue (default is true)
* @return string the rendered content
*/
public function getBodyHtml(bool $clear = true): string
{
// Register any asset bundles
$this->registerAllAssetFiles();
// Get the rendered body begin+end HTML
$html = $this->renderBodyBeginHtml() .
$this->renderBodyEndHtml(true);
// Clear out the queued up files
if ($clear === true) {
unset(
$this->jsFiles[self::POS_BEGIN],
$this->jsFiles[self::POS_END],
$this->js[self::POS_BEGIN],
$this->js[self::POS_END],
$this->js[self::POS_READY],
$this->js[self::POS_LOAD]
);
}
return $html;
}
/**
* Translates messages for a given translation category, so they will be
* available for `Craft.t()` calls in the Control Panel.
* Note this should always be called *before* any JavaScript is registered
* that will need to use the translations, unless the JavaScript is
* registered at [[self::POS_READY]].
*
* @param string $category The category the messages are in
* @param string[] $messages The messages to be translated
*/
public function registerTranslations(string $category, array $messages)
{
$jsCategory = Json::encode($category);
$js = '';