Namespaces

  • Latte
    • Loaders
    • Macros
    • Runtime
  • Nette
    • Application
      • Responses
      • Routers
      • UI
    • Bridges
      • ApplicationDI
      • ApplicationLatte
      • ApplicationTracy
      • CacheDI
      • CacheLatte
      • DatabaseDI
      • DatabaseTracy
      • DITracy
      • FormsDI
      • FormsLatte
      • Framework
      • HttpDI
      • HttpTracy
      • MailDI
      • ReflectionDI
      • SecurityDI
      • SecurityTracy
    • Caching
      • Storages
    • ComponentModel
    • Database
      • Conventions
      • Drivers
      • Reflection
      • Table
    • DI
      • Config
        • Adapters
      • Extensions
    • Diagnostics
    • Forms
      • Controls
      • Rendering
    • Http
    • Iterators
    • Latte
    • Loaders
    • Localization
    • Mail
    • Neon
    • PhpGenerator
    • Reflection
    • Security
    • Templating
    • Utils
  • NetteModule
  • none
  • Tracy
    • Bridges
      • Nette

Classes

  • BlockMacros
  • BlockMacrosRuntime
  • CoreMacros
  • MacroSet
  • Overview
  • Namespace
  • Class
  • Tree
  • Deprecated
  1: <?php
  2: 
  3: /**
  4:  * This file is part of the Latte (http://latte.nette.org)
  5:  * Copyright (c) 2008 David Grudl (http://davidgrudl.com)
  6:  */
  7: 
  8: namespace Latte\Macros;
  9: 
 10: use Latte;
 11: use Latte\MacroNode;
 12: use Latte\PhpWriter;
 13: use Latte\CompileException;
 14: 
 15: 
 16: /**
 17:  * Block macros.
 18:  */
 19: class BlockMacros extends MacroSet
 20: {
 21:     /** @var array */
 22:     private $namedBlocks = array();
 23: 
 24:     /** @var bool */
 25:     private $extends;
 26: 
 27: 
 28:     public static function install(Latte\Compiler $compiler)
 29:     {
 30:         $me = new static($compiler);
 31:         $me->addMacro('include', array($me, 'macroInclude'));
 32:         $me->addMacro('includeblock', array($me, 'macroIncludeBlock'));
 33:         $me->addMacro('extends', array($me, 'macroExtends'));
 34:         $me->addMacro('layout', array($me, 'macroExtends'));
 35:         $me->addMacro('block', array($me, 'macroBlock'), array($me, 'macroBlockEnd'));
 36:         $me->addMacro('define', array($me, 'macroBlock'), array($me, 'macroBlockEnd'));
 37:         $me->addMacro('snippet', array($me, 'macroBlock'), array($me, 'macroBlockEnd'));
 38:         $me->addMacro('snippetArea', array($me, 'macroBlock'), array($me, 'macroBlockEnd'));
 39:         $me->addMacro('ifset', array($me, 'macroIfset'), '}');
 40:         $me->addMacro('elseifset', array($me, 'macroIfset'), '}');
 41:     }
 42: 
 43: 
 44:     /**
 45:      * Initializes before template parsing.
 46:      * @return void
 47:      */
 48:     public function initialize()
 49:     {
 50:         $this->namedBlocks = array();
 51:         $this->extends = NULL;
 52:     }
 53: 
 54: 
 55:     /**
 56:      * Finishes template parsing.
 57:      * @return array(prolog, epilog)
 58:      */
 59:     public function finalize()
 60:     {
 61:         // try close last block
 62:         $last = $this->getCompiler()->getMacroNode();
 63:         if ($last && $last->name === 'block') {
 64:             $this->getCompiler()->closeMacro($last->name);
 65:         }
 66: 
 67:         $epilog = $prolog = array();
 68: 
 69:         if ($this->namedBlocks) {
 70:             foreach ($this->namedBlocks as $name => $code) {
 71:                 $func = '_lb' . substr(md5($this->getCompiler()->getTemplateId() . $name), 0, 10) . '_' . preg_replace('#[^a-z0-9_]#i', '_', $name);
 72:                 $snippet = $name[0] === '_';
 73:                 $prolog[] = "//\n// block $name\n//\n"
 74:                     . "if (!function_exists(\$_b->blocks[" . var_export($name, TRUE) . "][] = '$func')) { "
 75:                     . "function $func(\$_b, \$_args) { foreach (\$_args as \$__k => \$__v) \$\$__k = \$__v"
 76:                     . ($snippet ? '; $_control->redrawControl(' . var_export((string) substr($name, 1), TRUE) . ', FALSE)' : '')
 77:                     . "\n?>$code<?php\n}}";
 78:             }
 79:             $prolog[] = "//\n// end of blocks\n//";
 80:         }
 81: 
 82:         if ($this->namedBlocks || $this->extends) {
 83:             $prolog[] = '// template extending';
 84: 
 85:             $prolog[] = '$_l->extends = '
 86:                 . ($this->extends ? $this->extends : 'empty($_g->extended) && isset($_control) && $_control instanceof Nette\Application\UI\Presenter ? $_control->findLayoutTemplateFile() : NULL')
 87:                 . '; $_g->extended = TRUE;';
 88: 
 89:             $prolog[] = 'if ($_l->extends) { ' . ($this->namedBlocks ? 'ob_start();' : 'return $template->renderChildTemplate($_l->extends, get_defined_vars());') . '}';
 90:         }
 91: 
 92:         return array(implode("\n\n", $prolog), implode("\n", $epilog));
 93:     }
 94: 
 95: 
 96:     /********************* macros ****************d*g**/
 97: 
 98: 
 99:     /**
100:      * {include #block}
101:      */
102:     public function macroInclude(MacroNode $node, PhpWriter $writer)
103:     {
104:         $destination = $node->tokenizer->fetchWord(); // destination [,] [params]
105:         if (!preg_match('~#|[\w-]+\z~A', $destination)) {
106:             return FALSE;
107:         }
108: 
109:         $destination = ltrim($destination, '#');
110:         $parent = $destination === 'parent';
111:         if ($destination === 'parent' || $destination === 'this') {
112:             for ($item = $node->parentNode; $item && $item->name !== 'block' && !isset($item->data->name); $item = $item->parentNode);
113:             if (!$item) {
114:                 throw new CompileException("Cannot include $destination block outside of any block.");
115:             }
116:             $destination = $item->data->name;
117:         }
118: 
119:         $name = strpos($destination, '$') === FALSE ? var_export($destination, TRUE) : $destination;
120:         if (isset($this->namedBlocks[$destination]) && !$parent) {
121:             $cmd = "call_user_func(reset(\$_b->blocks[$name]), \$_b, %node.array? + get_defined_vars())";
122:         } else {
123:             $cmd = 'Latte\Macros\BlockMacrosRuntime::callBlock' . ($parent ? 'Parent' : '') . "(\$_b, $name, %node.array? + " . ($parent ? 'get_defined_vars' : '$template->getParameters') . '())';
124:         }
125: 
126:         if ($node->modifiers) {
127:             return $writer->write("ob_start(); $cmd; echo %modify(ob_get_clean())");
128:         } else {
129:             return $writer->write($cmd);
130:         }
131:     }
132: 
133: 
134:     /**
135:      * {includeblock "file"}
136:      */
137:     public function macroIncludeBlock(MacroNode $node, PhpWriter $writer)
138:     {
139:         return $writer->write('ob_start(); $_b->templates[%var]->renderChildTemplate(%node.word, %node.array? + get_defined_vars()); echo rtrim(ob_get_clean())',
140:             $this->getCompiler()->getTemplateId());
141:     }
142: 
143: 
144:     /**
145:      * {extends auto | none | $var | "file"}
146:      */
147:     public function macroExtends(MacroNode $node, PhpWriter $writer)
148:     {
149:         if (!$node->args) {
150:             throw new CompileException("Missing destination in {{$node->name}}");
151:         }
152:         if (!empty($node->parentNode)) {
153:             throw new CompileException("{{$node->name}} must be placed outside any macro.");
154:         }
155:         if ($this->extends !== NULL) {
156:             throw new CompileException("Multiple {{$node->name}} declarations are not allowed.");
157:         }
158:         if ($node->args === 'none') {
159:             $this->extends = 'FALSE';
160:         } elseif ($node->args === 'auto') {
161:             $this->extends = '$_presenter->findLayoutTemplateFile()';
162:         } else {
163:             $this->extends = $writer->write('%node.word%node.args');
164:         }
165:         return;
166:     }
167: 
168: 
169:     /**
170:      * {block [[#]name]}
171:      * {snippet [name [,]] [tag]}
172:      * {snippetArea [name]}
173:      * {define [#]name}
174:      */
175:     public function macroBlock(MacroNode $node, PhpWriter $writer)
176:     {
177:         $name = $node->tokenizer->fetchWord();
178: 
179:         if ($node->name === '#') {
180:             trigger_error('Shortcut {#block} is deprecated.', E_USER_DEPRECATED);
181: 
182:         } elseif ($node->name === 'block' && $name === FALSE) { // anonymous block
183:             return $node->modifiers === '' ? '' : 'ob_start()';
184:         }
185: 
186:         $node->data->name = $name = ltrim($name, '#');
187:         if ($name == NULL) {
188:             if ($node->name === 'define') {
189:                 throw new CompileException('Missing block name.');
190:             }
191: 
192:         } elseif (strpos($name, '$') !== FALSE) { // dynamic block/snippet
193:             if ($node->name === 'snippet') {
194:                 for ($parent = $node->parentNode; $parent && !($parent->name === 'snippet' || $parent->name === 'snippetArea'); $parent = $parent->parentNode);
195:                 if (!$parent) {
196:                     throw new CompileException('Dynamic snippets are allowed only inside static snippet/snippetArea.');
197:                 }
198:                 $parent->data->dynamic = TRUE;
199:                 $node->data->leave = TRUE;
200:                 $node->closingCode = "<?php \$_l->dynSnippets[\$_l->dynSnippetId] = ob_get_flush() ?>";
201: 
202:                 if ($node->prefix) {
203:                     $node->attrCode = $writer->write("<?php echo ' id=\"' . (\$_l->dynSnippetId = \$_control->getSnippetId({$writer->formatWord($name)})) . '\"' ?>");
204:                     return $writer->write('ob_start()');
205:                 }
206:                 $tag = trim($node->tokenizer->fetchWord(), '<>');
207:                 $tag = $tag ? $tag : 'div';
208:                 $node->closingCode .= "\n</$tag>";
209:                 return $writer->write("?>\n<$tag id=\"<?php echo \$_l->dynSnippetId = \$_control->getSnippetId({$writer->formatWord($name)}) ?>\"><?php ob_start()");
210: 
211:             } else {
212:                 $node->data->leave = TRUE;
213:                 $fname = $writer->formatWord($name);
214:                 $node->closingCode = '<?php }} ' . ($node->name === 'define' ? '' : "call_user_func(reset(\$_b->blocks[$fname]), \$_b, get_defined_vars())") . ' ?>';
215:                 $func = '_lb' . substr(md5($this->getCompiler()->getTemplateId() . $name), 0, 10) . '_' . preg_replace('#[^a-z0-9_]#i', '_', $name);
216:                 return "\n\n//\n// block $name\n//\n"
217:                     . "if (!function_exists(\$_b->blocks[$fname]['{$this->getCompiler()->getTemplateId()}'] = '$func')) { "
218:                     . "function $func(\$_b, \$_args) { foreach (\$_args as \$__k => \$__v) \$\$__k = \$__v";
219:             }
220:         }
221: 
222:         // static snippet/snippetArea
223:         if ($node->name === 'snippet' || $node->name === 'snippetArea') {
224:             if ($node->prefix && isset($node->htmlNode->attrs['id'])) {
225:                 throw new CompileException('Cannot combine HTML attribute id with n:snippet.');
226:             }
227:             $node->data->name = $name = '_' . $name;
228:         }
229: 
230:         if (isset($this->namedBlocks[$name])) {
231:             throw new CompileException("Cannot redeclare static {$node->name} '$name'");
232:         }
233: 
234:         $prolog = $this->namedBlocks ? '' : "if (\$_l->extends) { ob_end_clean(); return \$template->renderChildTemplate(\$_l->extends, get_defined_vars()); }\n";
235:         $this->namedBlocks[$name] = TRUE;
236: 
237:         $include = 'call_user_func(reset($_b->blocks[%var]), $_b, ' . (($node->name === 'snippet' || $node->name === 'snippetArea') ? '$template->getParameters()' : 'get_defined_vars()') . ')';
238:         if ($node->modifiers) {
239:             $include = "ob_start(); $include; echo %modify(ob_get_clean())";
240:         }
241: 
242:         if ($node->name === 'snippet') {
243:             if ($node->prefix) {
244:                 $node->attrCode = $writer->write('<?php echo \' id="\' . $_control->getSnippetId(%var) . \'"\' ?>', (string) substr($name, 1));
245:                 return $writer->write($prolog . $include, $name);
246:             }
247:             $tag = trim($node->tokenizer->fetchWord(), '<>');
248:             $tag = $tag ? $tag : 'div';
249:             return $writer->write("$prolog ?>\n<$tag id=\"<?php echo \$_control->getSnippetId(%var) ?>\"><?php $include ?>\n</$tag><?php ",
250:                 (string) substr($name, 1), $name
251:             );
252: 
253:         } elseif ($node->name === 'define') {
254:             return $prolog;
255: 
256:         } else { // block, snippetArea
257:             return $writer->write($prolog . $include, $name);
258:         }
259:     }
260: 
261: 
262:     /**
263:      * {/block}
264:      * {/snippet}
265:      * {/snippetArea}
266:      * {/define}
267:      */
268:     public function macroBlockEnd(MacroNode $node, PhpWriter $writer)
269:     {
270:         if (isset($node->data->name)) { // block, snippet, define
271:             if ($node->name === 'snippet' && $node->prefix === MacroNode::PREFIX_NONE // n:snippet -> n:inner-snippet
272:                 && preg_match('#^.*? n:\w+>\n?#s', $node->content, $m1) && preg_match('#[ \t]*<[^<]+\z#s', $node->content, $m2)
273:             ) {
274:                 $node->openingCode = $m1[0] . $node->openingCode;
275:                 $node->content = substr($node->content, strlen($m1[0]), -strlen($m2[0]));
276:                 $node->closingCode .= $m2[0];
277:             }
278: 
279:             if (empty($node->data->leave)) {
280:                 if ($node->name === 'snippetArea') {
281:                     $node->content = "<?php \$_control->snippetMode = isset(\$_snippetMode) && \$_snippetMode; ?>{$node->content}<?php \$_control->snippetMode = FALSE; ?>";
282:                 }
283:                 if (!empty($node->data->dynamic)) {
284:                     $node->content .= '<?php if (isset($_l->dynSnippets)) return $_l->dynSnippets; ?>';
285:                 }
286:                 if ($node->name === 'snippetArea') {
287:                     $node->content .= '<?php return FALSE; ?>';
288:                 }
289:                 $this->namedBlocks[$node->data->name] = $tmp = rtrim(ltrim($node->content, "\n"), " \t");
290:                 $node->content = substr_replace($node->content, $node->openingCode . "\n", strspn($node->content, "\n"), strlen($tmp));
291:                 $node->openingCode = '<?php ?>';
292:             }
293: 
294:         } elseif ($node->modifiers) { // anonymous block with modifier
295:             return $writer->write('echo %modify(ob_get_clean())');
296:         }
297:     }
298: 
299: 
300:     /**
301:      * {ifset #block}
302:      * {elseifset #block}
303:      */
304:     public function macroIfset(MacroNode $node, PhpWriter $writer)
305:     {
306:         if (!preg_match('~#|[\w-]+\z~A', $node->args)) {
307:             return FALSE;
308:         }
309:         $list = array();
310:         while (($name = $node->tokenizer->fetchWord()) !== FALSE) {
311:             $list[] = preg_match('~#|[\w-]+\z~A', $name)
312:                 ? '$_b->blocks["' . ltrim($name, '#') . '"]'
313:                 : $writer->formatArgs(new Latte\MacroTokens($name));
314:         }
315:         return ($node->name === 'elseifset' ? '} else' : '')
316:             . 'if (isset(' . implode(', ', $list) . ')) {';
317:     }
318: 
319: }
320: 
Nette 2.3.4 API API documentation generated by ApiGen 2.8.0