0e9ad8cc789886bcacb538918012e8342c59747c
[Packages/TYPO3.CMS.git] / typo3 / sysext / fluid / Classes / View / TemplateView.php
1 <?php
2
3 /* *
4 * This script belongs to the FLOW3 package "Fluid". *
5 * *
6 * It is free software; you can redistribute it and/or modify it under *
7 * the terms of the GNU Lesser General Public License as published by the *
8 * Free Software Foundation, either version 3 of the License, or (at your *
9 * option) any later version. *
10 * *
11 * This script is distributed in the hope that it will be useful, but *
12 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHAN- *
13 * TABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser *
14 * General Public License for more details. *
15 * *
16 * You should have received a copy of the GNU Lesser General Public *
17 * License along with the script. *
18 * If not, see http://www.gnu.org/licenses/lgpl.html *
19 * *
20 * The TYPO3 project - inspiring people to share! *
21 * */
22
23 /**
24 * The main template view. Should be used as view if you want Fluid Templating
25 *
26 * @version $Id: TemplateView.php 2043 2010-03-16 08:49:45Z sebastian $
27 * @package Fluid
28 * @subpackage View
29 * @license http://www.gnu.org/licenses/lgpl.html GNU Lesser General Public License, version 3 or later
30 * @api
31 * @scope prototype
32 */
33 class Tx_Fluid_View_TemplateView extends Tx_Extbase_MVC_View_AbstractView implements Tx_Fluid_View_TemplateViewInterface {
34
35 /**
36 * @var Tx_Fluid_Core_Parser_TemplateParser
37 */
38 protected $templateParser;
39
40 /**
41 * Pattern to be resolved for @templateRoot in the other patterns.
42 * @var string
43 */
44 protected $templateRootPathPattern = '@packageResourcesPath/Private/Templates';
45
46 /**
47 * Pattern to be resolved for @partialRoot in the other patterns.
48 * @var string
49 */
50 protected $partialRootPathPattern = '@packageResourcesPath/Private/Partials';
51
52 /**
53 * Pattern to be resolved for @layoutRoot in the other patterns.
54 * @var string
55 */
56 protected $layoutRootPathPattern = '@packageResourcesPath/Private/Layouts';
57
58 /**
59 * Path to the template root. If NULL, then $this->templateRootPathPattern will be used.
60 * @var string
61 */
62 protected $templateRootPath = NULL;
63
64 /**
65 * Path to the partial root. If NULL, then $this->partialRootPathPattern will be used.
66 * @var string
67 */
68 protected $partialRootPath = NULL;
69
70 /**
71 * Path to the layout root. If NULL, then $this->layoutRootPathPattern will be used.
72 * @var string
73 */
74 protected $layoutRootPath = NULL;
75
76 /**
77 * File pattern for resolving the template file
78 * @var string
79 */
80 protected $templatePathAndFilenamePattern = '@templateRoot/@controller/@action.@format';
81
82 /**
83 * Directory pattern for global partials. Not part of the public API, should not be changed for now.
84 * @var string
85 */
86 private $partialPathAndFilenamePattern = '@partialRoot/@partial.@format';
87
88 /**
89 * File pattern for resolving the layout
90 * @var string
91 */
92 protected $layoutPathAndFilenamePattern = '@layoutRoot/@layout.@format';
93
94 /**
95 * Path and filename of the template file. If set, overrides the templatePathAndFilenamePattern
96 * @var string
97 */
98 protected $templatePathAndFilename = NULL;
99
100 /**
101 * Path and filename of the layout file. If set, overrides the layoutPathAndFilenamePattern
102 * @var string
103 */
104 protected $layoutPathAndFilename = NULL;
105
106 public function __construct() {
107 $this->templateParser = Tx_Fluid_Compatibility_TemplateParserBuilder::build();
108 $this->objectManager = t3lib_div::makeInstance('Tx_Fluid_Compatibility_ObjectManager');
109 }
110 // Here, the backporter can insert a constructor method, which is needed for Fluid v4.
111
112 /**
113 * Inject the template parser
114 *
115 * @param Tx_Fluid_Core_Parser_TemplateParser $templateParser The template parser
116 * @return void
117 * @author Sebastian Kurfürst <sebastian@typo3.org>
118 */
119 public function injectTemplateParser(Tx_Fluid_Core_Parser_TemplateParser $templateParser) {
120 $this->templateParser = $templateParser;
121 }
122
123 /**
124 * Initialize view
125 *
126 * @return void
127 * @author Sebastian Kurfürst <sebastian@typo3.org>
128 * @api
129 */
130 public function initializeView() {
131 }
132
133 /**
134 * Sets the path and name of of the template file. Effectively overrides the
135 * dynamic resolving of a template file.
136 *
137 * @param string $templatePathAndFilename Template file path
138 * @return void
139 * @author Sebastian Kurfürst <sebastian@typo3.org>
140 * @api
141 */
142 public function setTemplatePathAndFilename($templatePathAndFilename) {
143 $this->templatePathAndFilename = $templatePathAndFilename;
144 }
145
146 /**
147 * Sets the path and name of the layout file. Overrides the dynamic resolving of the layout file.
148 *
149 * @param string $layoutPathAndFilename Path and filename of the layout file
150 * @return void
151 * @author Sebastian Kurfürst <sebastian@typo3.org>
152 * @api
153 */
154 public function setLayoutPathAndFilename($layoutPathAndFilename) {
155 $this->layoutPathAndFilename = $layoutPathAndFilename;
156 }
157
158 /**
159 * Build the rendering context
160 *
161 * @param Tx_Fluid_Core_ViewHelper_TemplateVariableContainer $variableContainer
162 * @return Tx_Fluid_Core_Rendering_RenderingContext
163 * @author Sebastian Kurfürst <sebastian@typo3.org>
164 */
165 protected function buildRenderingContext(Tx_Fluid_Core_ViewHelper_TemplateVariableContainer $variableContainer = NULL) {
166 if ($variableContainer === NULL) {
167 $variableContainer = $this->objectManager->create('Tx_Fluid_Core_ViewHelper_TemplateVariableContainer', $this->variables);
168 }
169
170 $renderingContext = $this->objectManager->create('Tx_Fluid_Core_Rendering_RenderingContext');
171 $renderingContext->setTemplateVariableContainer($variableContainer);
172 if ($this->controllerContext !== NULL) {
173 $renderingContext->setControllerContext($this->controllerContext);
174 }
175
176 $viewHelperVariableContainer = $this->objectManager->create('Tx_Fluid_Core_ViewHelper_ViewHelperVariableContainer');
177 $viewHelperVariableContainer->setView($this);
178 $renderingContext->setViewHelperVariableContainer($viewHelperVariableContainer);
179
180 return $renderingContext;
181 }
182
183 /**
184 * Build parser configuration
185 *
186 * @return Tx_Fluid_Core_Parser_Configuration
187 * @author Karsten Dambekalns <karsten@typo3.org>
188 */
189 protected function buildParserConfiguration() {
190 $parserConfiguration = $this->objectManager->create('Tx_Fluid_Core_Parser_Configuration');
191 if ($this->controllerContext->getRequest()->getFormat() === 'html') {
192 $parserConfiguration->addInterceptor($this->objectManager->get('Tx_Fluid_Core_Parser_Interceptor_Escape'));
193
194 }
195 return $parserConfiguration;
196 }
197
198 /**
199 * Find the XHTML template according to $this->templatePathAndFilenamePattern and render the template.
200 * If "layoutName" is set in a PostParseFacet callback, it will render the file with the given layout.
201 *
202 * @param string $actionName If set, the view of the specified action will be rendered instead. Default is the action specified in the Request object
203 * @return string Rendered Template
204 * @author Sebastian Kurfürst <sebastian@typo3.org>
205 * @api
206 */
207 public function render($actionName = NULL) {
208 $templatePathAndFilename = $this->resolveTemplatePathAndFilename($actionName);
209
210 $this->templateParser->setConfiguration($this->buildParserConfiguration());
211 $parsedTemplate = $this->parseTemplate($templatePathAndFilename);
212
213 $variableContainer = $parsedTemplate->getVariableContainer();
214 if ($variableContainer !== NULL && $variableContainer->exists('layoutName')) {
215 return $this->renderWithLayout($variableContainer->get('layoutName'));
216 }
217
218 return $parsedTemplate->render($this->buildRenderingContext());
219 }
220
221 /**
222 * Resolve the template path and filename for the given action. If action is null, looks into the current request.
223 *
224 * @param string $actionName Name of the action. If NULL, will be taken from request.
225 * @return string Full path to template
226 * @author Sebastian Kurfürst <sebastian@typo3.org>
227 */
228 protected function resolveTemplatePathAndFilename($actionName = NULL) {
229 if ($this->templatePathAndFilename !== NULL) {
230 return $this->templatePathAndFilename;
231 }
232
233 $actionName = ($actionName !== NULL ? $actionName : $this->controllerContext->getRequest()->getControllerActionName());
234 $actionName = strtolower($actionName);
235
236 $paths = $this->expandGenericPathPattern($this->templatePathAndFilenamePattern, FALSE, FALSE);
237
238 foreach ($paths as &$path) {
239 $path = str_replace('@action', $actionName, $path);
240 if (file_exists($path)) {
241 return $path;
242 }
243 }
244 throw new RuntimeException('The template files "' . implode('", "', $paths) . '" could not be loaded.', 1225709595);
245 }
246
247 /**
248 * Renders a given section.
249 *
250 * @param string $sectionName Name of section to render
251 * @return string rendered template for the section
252 * @author Sebastian Kurfürst <sebastian@typo3.org>
253 * @author Bastian Waidelich <bastian@typo3.org>
254 */
255 public function renderSection($sectionName) {
256 $parsedTemplate = $this->parseTemplate($this->resolveTemplatePathAndFilename());
257
258 $sections = $parsedTemplate->getVariableContainer()->get('sections');
259 if(!array_key_exists($sectionName, $sections)) {
260 throw new RuntimeException('The given section does not exist!', 1227108982);
261 }
262 $section = $sections[$sectionName];
263
264 $renderingContext = $this->buildRenderingContext();
265 $section->setRenderingContext($renderingContext);
266 return $section->evaluate();
267 }
268
269 /**
270 * Render a template with a given layout.
271 *
272 * @param string $layoutName Name of layout
273 * @return string rendered HTML
274 * @author Sebastian Kurfürst <sebastian@typo3.org>
275 * @author Bastian Waidelich <bastian@typo3.org>
276 */
277 public function renderWithLayout($layoutName) {
278 $parsedTemplate = $this->parseTemplate($this->resolveLayoutPathAndFilename($layoutName));
279
280 $renderingContext = $this->buildRenderingContext();
281 return $parsedTemplate->render($renderingContext);
282 }
283
284 /**
285 * Resolve the path and file name of the layout file, based on
286 * $this->layoutPathAndFilename and $this->layoutPathAndFilenamePattern.
287 *
288 * In case a layout has already been set with setLayoutPathAndFilename(),
289 * this method returns that path, otherwise a path and filename will be
290 * resolved using the layoutPathAndFilenamePattern.
291 *
292 * @param string $layoutName Name of the layout to use. If none given, use "default"
293 * @return string Path and filename of layout file
294 * @author Sebastian Kurfürst <sebastian@typo3.org>
295 */
296 protected function resolveLayoutPathAndFilename($layoutName = 'default') {
297 if ($this->layoutPathAndFilename) {
298 return $this->layoutPathAndFilename;
299 }
300
301 $paths = $this->expandGenericPathPattern($this->layoutPathAndFilenamePattern, TRUE, TRUE);
302 foreach ($paths as &$path) {
303 $path = str_replace('@layout', $layoutName, $path);
304 if (file_exists($path)) {
305 return $path;
306 }
307 }
308 throw new RuntimeException('The template files "' . implode('", "', $paths) . '" could not be loaded.', 1225709595);
309 }
310
311 /**
312 * Renders a partial.
313 *
314 * @param string $partialName
315 * @param string $sectionToRender
316 * @param array $variables
317 * @return string
318 * @author Sebastian Kurfürst <sebastian@typo3.org>
319 * @author Bastian Waidelich <bastian@typo3.org>
320 * @author Robert Lemke <robert@typo3.org>
321 */
322 public function renderPartial($partialName, $sectionToRender, array $variables) {
323 $partial = $this->parseTemplate($this->resolvePartialPathAndFilename($partialName));
324 $variableContainer = $this->objectManager->create('Tx_Fluid_Core_ViewHelper_TemplateVariableContainer', $variables);
325 $renderingContext = $this->buildRenderingContext($variableContainer);
326 return $partial->render($renderingContext);
327 }
328
329 /**
330 * Figures out which partial to use.
331 *
332 * @param string $partialName The name of the partial
333 * @return string the full path which should be used. The path definitely exists.
334 * @author Sebastian Kurfürst <sebastian@typo3.org>
335 */
336 protected function resolvePartialPathAndFilename($partialName) {
337 $paths = $this->expandGenericPathPattern($this->partialPathAndFilenamePattern, TRUE, TRUE);
338 foreach ($paths as &$path) {
339 $path = str_replace('@partial', $partialName, $path);
340 if (file_exists($path)) {
341 return $path;
342 }
343 }
344 throw new RuntimeException('The template files "' . implode('", "', $paths) . '" could not be loaded.', 1225709595);
345 }
346
347 /**
348 * Checks whether a template can be resolved for the current request context.
349 *
350 * @return boolean
351 * @author Karsten Dambekalns <karsten@typo3.org>
352 * @author Sebastian Kurfürst <sebastian@typo3.org>
353 * @api
354 */
355 public function hasTemplate() {
356 try {
357 $this->resolveTemplatePathAndFilename();
358 return TRUE;
359 } catch (RuntimeException $e) {
360 return FALSE;
361 }
362 }
363
364 /**
365 * Parse the given template and return it.
366 *
367 * Will cache the results for one call.
368 *
369 * @param string $templatePathAndFilename absolute filename of the template to be parsed
370 * @return Tx_Fluid_Core_Parser_ParsedTemplateInterface the parsed template tree
371 * @throws Tx_Fluid_View_Exception_InvalidTemplateResourceException
372 * @author Sebastian Kurfürst <sebastian@typo3.org>
373 */
374 protected function parseTemplate($templatePathAndFilename) {
375 $templateSource = file_get_contents($templatePathAndFilename);
376 if ($templateSource === FALSE) {
377 throw new Tx_Fluid_View_Exception_InvalidTemplateResourceException('"' . $templatePathAndFilename . '" is not a valid template resource URI.', 1257246929);
378 }
379 return $this->templateParser->parse($templateSource);
380 }
381
382 /**
383 * Set the root path to the templates.
384 * If set, overrides the one determined from $this->templateRootPathPattern
385 *
386 * @param string $templateRootPath Root path to the templates. If set, overrides the one determined from $this->templateRootPathPattern
387 * @return void
388 * @author Sebastian Kurfürst <sebastian@typo3.org>
389 * @api
390 */
391 public function setTemplateRootPath($templateRootPath) {
392 $this->templateRootPath = $templateRootPath;
393 }
394
395 /**
396 * Resolves the template root to be used inside other paths.
397 *
398 * @return string Path to template root directory
399 * @author Sebastian Kurfürst <sebastian@typo3.org>
400 */
401 protected function getTemplateRootPath() {
402 if ($this->templateRootPath !== NULL) {
403 return $this->templateRootPath;
404 } else {
405 return str_replace('@packageResourcesPath', t3lib_extMgm::extPath($this->controllerContext->getRequest()->getControllerExtensionKey()) . 'Resources/', $this->templateRootPathPattern);
406 }
407 }
408
409 /**
410 * Set the root path to the partials.
411 * If set, overrides the one determined from $this->partialRootPathPattern
412 *
413 * @param string $partialRootPath Root path to the partials. If set, overrides the one determined from $this->partialRootPathPattern
414 * @return void
415 * @author Bastian Waidelich <bastian@typo3.org>
416 * @api
417 */
418 public function setPartialRootPath($partialRootPath) {
419 $this->partialRootPath = $partialRootPath;
420 }
421
422 /**
423 * Resolves the partial root to be used inside other paths.
424 *
425 * @return string Path to partial root directory
426 * @author Bastian Waidelich <bastian@typo3.org>
427 */
428 protected function getPartialRootPath() {
429 if ($this->partialRootPath !== NULL) {
430 return $this->partialRootPath;
431 } else {
432 return str_replace('@packageResourcesPath', t3lib_extMgm::extPath($this->controllerContext->getRequest()->getControllerExtensionKey()) . 'Resources/', $this->partialRootPathPattern);
433 }
434 }
435
436 /**
437 * Set the root path to the layouts.
438 * If set, overrides the one determined from $this->layoutRootPathPattern
439 *
440 * @param string $layoutRootPath Root path to the layouts. If set, overrides the one determined from $this->layoutRootPathPattern
441 * @return void
442 * @author Bastian Waidelich <bastian@typo3.org>
443 * @api
444 */
445 public function setLayoutRootPath($layoutRootPath) {
446 $this->layoutRootPath = $layoutRootPath;
447 }
448
449 /**
450 * Resolves the layout root to be used inside other paths.
451 *
452 * @return string Path to layout root directory
453 * @author Bastian Waidelich <bastian@typo3.org>
454 */
455 protected function getLayoutRootPath() {
456 if ($this->layoutRootPath !== NULL) {
457 return $this->layoutRootPath;
458 } else {
459 return str_replace('@packageResourcesPath', t3lib_extMgm::extPath($this->controllerContext->getRequest()->getControllerExtensionKey()) . 'Resources/', $this->layoutRootPathPattern);
460 }
461 }
462
463 /**
464 * Processes @templateRoot, @subpackage, @controller, and @format placeholders inside $pattern.
465 * This method is used to generate "fallback chains" for file system locations where a certain Partial can reside.
466 *
467 * If $bubbleControllerAndSubpackage is FALSE and $formatIsOptional is FALSE, then the resulting array will only have one element
468 * with all the above placeholders replaced.
469 *
470 * If you set $bubbleControllerAndSubpackage to TRUE, then you will get an array with potentially many elements:
471 * The first element of the array is like above. The second element has the @controller part set to "" (the empty string)
472 * The third element now has the @controller part again stripped off, and has the last subpackage part stripped off as well.
473 * This continues until both @subpackage and @controller are empty.
474 *
475 * Example for $bubbleControllerAndSubpackage is TRUE, we have the Tx_Fluid_MySubPackage_Controller_MyController as Controller Object Name and the current format is "html"
476 * If pattern is @templateRoot/@controller/@action.@format, then the resulting array is:
477 * - Resources/Private/Templates/MySubPackage/My/@action.html
478 * - Resources/Private/Templates/MySubPackage/@action.html
479 * - Resources/Private/Templates/@action.html
480 *
481 * If you set $formatIsOptional to TRUE, then for any of the above arrays, every element will be duplicated - once with @format
482 * replaced by the current request format, and once with .@format stripped off.
483 *
484 * @param string $pattern Pattern to be resolved
485 * @param boolean $bubbleControllerAndSubpackage if TRUE, then we successively split off parts from @controller and @subpackage until both are empty.
486 * @param boolean $formatIsOptional if TRUE, then half of the resulting strings will have .@format stripped off, and the other half will have it.
487 * @return array unix style path
488 * @author Sebastian Kurfürst <sebastian@typo3.org>
489 * @author Robert Lemke <robert@typo3.org>
490 */
491 protected function expandGenericPathPattern($pattern, $bubbleControllerAndSubpackage, $formatIsOptional) {
492 $pattern = str_replace('@templateRoot', $this->getTemplateRootPath(), $pattern);
493 $pattern = str_replace('@partialRoot', $this->getPartialRootPath(), $pattern);
494 $pattern = str_replace('@layoutRoot', $this->getLayoutRootPath(), $pattern);
495
496 $subPackageKey = '';
497 $controllerName = $this->controllerContext->getRequest()->getControllerName();
498
499 $subpackageParts = ($subPackageKey !== '') ? explode(Tx_Fluid_Fluid::NAMESPACE_SEPARATOR, $subPackageKey) : array();
500
501 $results = array();
502
503 if ($controllerName !== NULL) {
504 $i = -1;
505 } else {
506 $i = 0;
507 }
508
509 do {
510 $temporaryPattern = $pattern;
511 if ($i < 0) {
512 $temporaryPattern = str_replace('@controller', $controllerName, $temporaryPattern);
513 } else {
514 $temporaryPattern = str_replace('//', '/', str_replace('@controller', '', $temporaryPattern));
515 }
516 $temporaryPattern = str_replace('@subpackage', implode('/', ($i<0 ? $subpackageParts : array_slice($subpackageParts, $i))), $temporaryPattern);
517
518 $results[] = t3lib_div::fixWindowsFilePath(str_replace('@format', $this->controllerContext->getRequest()->getFormat(), $temporaryPattern));
519 if ($formatIsOptional) {
520 $results[] = t3lib_div::fixWindowsFilePath(str_replace('.@format', '', $temporaryPattern));
521 }
522
523 } while($i++ < count($subpackageParts) && $bubbleControllerAndSubpackage);
524
525 return $results;
526 }
527 }
528
529 ?>