1: <?php
2:
3: /**
4: * This file is part of the Nette Framework (https://nette.org)
5: *
6: * Copyright (c) 2004 David Grudl (http://davidgrudl.com)
7: *
8: * For the full copyright and license information, please view
9: * the file license.txt that was distributed with this source code.
10: * @package Nette\Templates
11: */
12:
13:
14:
15: /**
16: * Control snippet template helper.
17: *
18: * @author David Grudl
19: * @package Nette\Templates
20: */
21: class NSnippetHelper extends NObject
22: {
23: /** @var bool */
24: public static $outputAllowed = TRUE;
25:
26: /** @var string */
27: private $id;
28:
29: /** @var string */
30: private $tag;
31:
32: /** @var NArrayObject */
33: private $payload;
34:
35: /** @var int */
36: private $level;
37:
38:
39:
40: /**
41: * Starts conditional snippet rendering. Returns SnippetHelper object if snippet was started.
42: * @param NControl control
43: * @param string snippet name
44: * @param string start element
45: * @return NSnippetHelper
46: */
47: public static function create(NControl $control, $name = NULL, $tag = 'div')
48: {
49: if (self::$outputAllowed) { // rendering flow or non-AJAX request
50: $obj = new self;
51: $obj->tag = trim($tag, '<>');
52: if ($obj->tag) echo '<', $obj->tag, ' id="', $control->getSnippetId($name), '">';
53: return $obj; // or string?
54:
55: } elseif ($control->isControlInvalid($name)) { // start snippet buffering
56: $obj = new self;
57: $obj->id = $control->getSnippetId($name);
58: $obj->payload = $control->getPresenter()->getPayload();
59: ob_start();
60: $obj->level = ob_get_level();
61: self::$outputAllowed = TRUE;
62: return $obj;
63:
64: } else {
65: return FALSE;
66: }
67: }
68:
69:
70:
71: /**
72: * Finishes and saves the snippet.
73: * @return void
74: */
75: public function finish()
76: {
77: if ($this->tag !== NULL) { // rendering flow or non-AJAX request
78: if ($this->tag) echo "</$this->tag>";
79:
80: } else { // finish snippet buffering
81: if ($this->level !== ob_get_level()) {
82: throw new InvalidStateException("Snippet '$this->id' cannot be ended here.");
83: }
84: $this->payload->snippets[$this->id] = ob_get_clean();
85: self::$outputAllowed = FALSE;
86: }
87: }
88:
89: }
90: