Namespaces

  • Nette
    • Application
      • Diagnostics
      • Responses
      • Routers
      • UI
    • Caching
      • Storages
    • ComponentModel
    • Config
      • Adapters
      • Extensions
    • Database
      • Diagnostics
      • Drivers
      • Reflection
      • Table
    • DI
      • Diagnostics
    • Diagnostics
    • Forms
      • Controls
      • Rendering
    • Http
    • Iterators
    • Latte
      • Macros
    • Loaders
    • Localization
    • Mail
    • Reflection
    • Security
      • Diagnostics
    • Templating
    • Utils
      • PhpGenerator
  • NetteModule
  • None
  • PHP

Classes

  • CacheMacro
  • CoreMacros
  • FormMacros
  • MacroSet
  • UIMacros
  • Overview
  • Namespace
  • Class
  • Tree
  1: <?php
  2: 
  3: /**
  4:  * This file is part of the Nette Framework (http://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:  */
 11: 
 12: namespace Nette\Latte\Macros;
 13: 
 14: use Nette,
 15:     Nette\Latte,
 16:     Nette\Latte\CompileException,
 17:     Nette\Latte\MacroNode;
 18: 
 19: 
 20: 
 21: /**
 22:  * Basic macros for Latte.
 23:  *
 24:  * - {if ?} ... {elseif ?} ... {else} ... {/if}
 25:  * - {ifset ?} ... {elseifset ?} ... {/ifset}
 26:  * - {for ?} ... {/for}
 27:  * - {foreach ?} ... {/foreach}
 28:  * - {$variable} with escaping
 29:  * - {!$variable} without escaping
 30:  * - {=expression} echo with escaping
 31:  * - {!=expression} echo without escaping
 32:  * - {?expression} evaluate PHP statement
 33:  * - {_expression} echo translation with escaping
 34:  * - {!_expression} echo translation without escaping
 35:  * - {attr ?} HTML element attributes
 36:  * - {capture ?} ... {/capture} capture block to parameter
 37:  * - {var var => value} set template parameter
 38:  * - {default var => value} set default template parameter
 39:  * - {dump $var}
 40:  * - {debugbreak}
 41:  * - {l} {r} to display { }
 42:  *
 43:  * @author     David Grudl
 44:  */
 45: class CoreMacros extends MacroSet
 46: {
 47: 
 48: 
 49:     public static function install(Latte\Compiler $compiler)
 50:     {
 51:         $me = new static($compiler);
 52: 
 53:         $me->addMacro('if', array($me, 'macroIf'), array($me, 'macroEndIf'));
 54:         $me->addMacro('elseif', 'elseif (%node.args):');
 55:         $me->addMacro('else', array($me, 'macroElse'));
 56:         $me->addMacro('ifset', 'if (isset(%node.args)):', 'endif');
 57:         $me->addMacro('elseifset', 'elseif (isset(%node.args)):');
 58: 
 59:         $me->addMacro('foreach', '', array($me, 'macroEndForeach'));
 60:         $me->addMacro('for', 'for (%node.args):', 'endfor');
 61:         $me->addMacro('while', 'while (%node.args):', 'endwhile');
 62:         $me->addMacro('continueIf', 'if (%node.args) continue');
 63:         $me->addMacro('breakIf', 'if (%node.args) break');
 64:         $me->addMacro('first', 'if ($iterator->isFirst(%node.args)):', 'endif');
 65:         $me->addMacro('last', 'if ($iterator->isLast(%node.args)):', 'endif');
 66:         $me->addMacro('sep', 'if (!$iterator->isLast(%node.args)):', 'endif');
 67: 
 68:         $me->addMacro('var', array($me, 'macroVar'));
 69:         $me->addMacro('assign', array($me, 'macroVar')); // deprecated
 70:         $me->addMacro('default', array($me, 'macroVar'));
 71:         $me->addMacro('dump', array($me, 'macroDump'));
 72:         $me->addMacro('debugbreak', array($me, 'macroDebugbreak'));
 73:         $me->addMacro('l', '?>{<?php');
 74:         $me->addMacro('r', '?>}<?php');
 75: 
 76:         $me->addMacro('_', array($me, 'macroTranslate'), array($me, 'macroTranslate'));
 77:         $me->addMacro('=', array($me, 'macroExpr'));
 78:         $me->addMacro('?', array($me, 'macroExpr'));
 79: 
 80:         $me->addMacro('capture', array($me, 'macroCapture'), array($me, 'macroCaptureEnd'));
 81:         $me->addMacro('include', array($me, 'macroInclude'));
 82:         $me->addMacro('use', array($me, 'macroUse'));
 83: 
 84:         $me->addMacro('class', NULL, NULL, array($me, 'macroClass'));
 85:         $me->addMacro('attr', array($me, 'macroOldAttr'), '', array($me, 'macroAttr'));
 86:         $me->addMacro('href', NULL); // TODO: placeholder
 87:     }
 88: 
 89: 
 90: 
 91:     /**
 92:      * Finishes template parsing.
 93:      * @return array(prolog, epilog)
 94:      */
 95:     public function finalize()
 96:     {
 97:         return array('list($_l, $_g) = Nette\Latte\Macros\CoreMacros::initRuntime($template, '
 98:             . var_export($this->getCompiler()->getTemplateId(), TRUE) . ')');
 99:     }
100: 
101: 
102: 
103:     /********************* macros ****************d*g**/
104: 
105: 
106: 
107:     /**
108:      * {if ...}
109:      */
110:     public function macroIf(MacroNode $node, $writer)
111:     {
112:         if ($node->data->capture = ($node->args === '')) {
113:             return 'ob_start()';
114:         }
115:         if ($node->htmlNode && isset($node->htmlNode->macroAttrs['tag-if'])) {
116:             return $writer->write($node->htmlNode->closing ? 'if (array_pop($_l->ifs)):' : 'if ($_l->ifs[] = (%node.args)):');
117:         }
118:         return $writer->write('if (%node.args):');
119:     }
120: 
121: 
122: 
123:     /**
124:      * {/if ...}
125:      */
126:     public function macroEndIf(MacroNode $node, $writer)
127:     {
128:         if ($node->data->capture) {
129:             if ($node->args === '') {
130:                 throw new CompileException('Missing condition in {if} macro.');
131:             }
132:             return $writer->write('if (%node.args) '
133:                 . (isset($node->data->else) ? '{ ob_end_clean(); ob_end_flush(); }' : 'ob_end_flush();')
134:                 . ' else '
135:                 . (isset($node->data->else) ? '{ $_else = ob_get_contents(); ob_end_clean(); ob_end_clean(); echo $_else; }' : 'ob_end_clean();')
136:             );
137:         }
138:         return 'endif';
139:     }
140: 
141: 
142: 
143:     /**
144:      * {else}
145:      */
146:     public function macroElse(MacroNode $node, $writer)
147:     {
148:         $ifNode = $node->parentNode;
149:         if ($ifNode && $ifNode->name === 'if' && $ifNode->data->capture) {
150:             if (isset($ifNode->data->else)) {
151:                 throw new CompileException("Macro {if} supports only one {else}.");
152:             }
153:             $ifNode->data->else = TRUE;
154:             return 'ob_start()';
155:         }
156:         return 'else:';
157:     }
158: 
159: 
160: 
161:     /**
162:      * {_$var |modifiers}
163:      */
164:     public function macroTranslate(MacroNode $node, $writer)
165:     {
166:         if ($node->closing) {
167:             return $writer->write('echo %modify($template->translate(ob_get_clean()))');
168: 
169:         } elseif ($node->isEmpty = ($node->args !== '')) {
170:             return $writer->write('echo %modify($template->translate(%node.args))');
171: 
172:         } else {
173:             return 'ob_start()';
174:         }
175:     }
176: 
177: 
178: 
179:     /**
180:      * {include "file" [,] [params]}
181:      */
182:     public function macroInclude(MacroNode $node, $writer)
183:     {
184:         $code = $writer->write('Nette\Latte\Macros\CoreMacros::includeTemplate(%node.word, %node.array? + $template->getParameters(), $_l->templates[%var])',
185:             $this->getCompiler()->getTemplateId());
186: 
187:         if ($node->modifiers) {
188:             return $writer->write('echo %modify(%raw->__toString(TRUE))', $code);
189:         } else {
190:             return $code . '->render()';
191:         }
192:     }
193: 
194: 
195: 
196:     /**
197:      * {use class MacroSet}
198:      */
199:     public function macroUse(MacroNode $node, $writer)
200:     {
201:         call_user_func(array($node->tokenizer->fetchWord(), 'install'), $this->getCompiler())
202:             ->initialize();
203:     }
204: 
205: 
206: 
207:     /**
208:      * {capture $variable}
209:      */
210:     public function macroCapture(MacroNode $node, $writer)
211:     {
212:         $variable = $node->tokenizer->fetchWord();
213:         if (substr($variable, 0, 1) !== '$') {
214:             throw new CompileException("Invalid capture block variable '$variable'");
215:         }
216:         $node->data->variable = $variable;
217:         return 'ob_start()';
218:     }
219: 
220: 
221: 
222:     /**
223:      * {/capture}
224:      */
225:     public function macroCaptureEnd(MacroNode $node, $writer)
226:     {
227:         return $writer->write("{$node->data->variable} = %modify(ob_get_clean())");
228:     }
229: 
230: 
231: 
232:     /**
233:      * {foreach ...}
234:      */
235:     public function macroEndForeach(MacroNode $node, $writer)
236:     {
237:         if (preg_match('#\W(\$iterator|include|require|get_defined_vars)\W#', $this->getCompiler()->expandTokens($node->content))) {
238:             $node->openingCode = '<?php $iterations = 0; foreach ($iterator = $_l->its[] = new Nette\Iterators\CachingIterator('
239:             . preg_replace('#(.*)\s+as\s+#i', '$1) as ', $writer->formatArgs(), 1) . '): ?>';
240:             $node->closingCode = '<?php $iterations++; endforeach; array_pop($_l->its); $iterator = end($_l->its) ?>';
241:         } else {
242:             $node->openingCode = '<?php $iterations = 0; foreach (' . $writer->formatArgs() . '): ?>';
243:             $node->closingCode = '<?php $iterations++; endforeach ?>';
244:         }
245:     }
246: 
247: 
248: 
249:     /**
250:      * n:class="..."
251:      */
252:     public function macroClass(MacroNode $node, $writer)
253:     {
254:         return $writer->write('if ($_l->tmp = array_filter(%node.array)) echo \' class="\' . %escape(implode(" ", array_unique($_l->tmp))) . \'"\'');
255:     }
256: 
257: 
258: 
259:     /**
260:      * n:attr="..."
261:      */
262:     public function macroAttr(MacroNode $node, $writer)
263:     {
264:         return $writer->write('echo Nette\Utils\Html::el(NULL, %node.array)->attributes()');
265:     }
266: 
267: 
268: 
269:     /**
270:      * {attr ...}
271:      * @deprecated
272:      */
273:     public function macroOldAttr(MacroNode $node)
274:     {
275:         return Nette\Utils\Strings::replace($node->args . ' ', '#\)\s+#', ')->');
276:     }
277: 
278: 
279: 
280:     /**
281:      * {dump ...}
282:      */
283:     public function macroDump(MacroNode $node, $writer)
284:     {
285:         $args = $writer->formatArgs();
286:         return $writer->write('Nette\Diagnostics\Debugger::barDump(' . ($node->args ? "array(%var => $args)" : 'get_defined_vars()')
287:             . ', "Template " . str_replace(dirname(dirname($template->getFile())), "\xE2\x80\xA6", $template->getFile()))', $args);
288:     }
289: 
290: 
291: 
292:     /**
293:      * {debugbreak ...}
294:      */
295:     public function macroDebugbreak(MacroNode $node, $writer)
296:     {
297:         return $writer->write(($node->args == NULL ? '' : 'if (!(%node.args)); else')
298:             . 'if (function_exists("debugbreak")) debugbreak(); elseif (function_exists("xdebug_break")) xdebug_break()');
299:     }
300: 
301: 
302: 
303:     /**
304:      * {var ...}
305:      * {default ...}
306:      */
307:     public function macroVar(MacroNode $node, $writer)
308:     {
309:         $out = '';
310:         $var = TRUE;
311:         $tokenizer = $writer->preprocess();
312:         while ($token = $tokenizer->fetchToken()) {
313:             if ($var && ($token['type'] === Latte\MacroTokenizer::T_SYMBOL || $token['type'] === Latte\MacroTokenizer::T_VARIABLE)) {
314:                 if ($node->name === 'default') {
315:                     $out .= "'" . ltrim($token['value'], "$") . "'";
316:                 } else {
317:                     $out .= '$' . ltrim($token['value'], "$");
318:                 }
319:                 $var = NULL;
320: 
321:             } elseif (($token['value'] === '=' || $token['value'] === '=>') && $token['depth'] === 0) {
322:                 $out .= $node->name === 'default' ? '=>' : '=';
323:                 $var = FALSE;
324: 
325:             } elseif ($token['value'] === ',' && $token['depth'] === 0) {
326:                 $out .= $node->name === 'default' ? ',' : ';';
327:                 $var = TRUE;
328: 
329:             } elseif ($var === NULL && $node->name === 'default' && $token['type'] !== Latte\MacroTokenizer::T_WHITESPACE) {
330:                 throw new CompileException("Unexpected '$token[value]' in {default $node->args}");
331: 
332:             } else {
333:                 $out .= $writer->canQuote($tokenizer) ? "'$token[value]'" : $token['value'];
334:             }
335:         }
336:         return $node->name === 'default' ? "extract(array($out), EXTR_SKIP)" : $out;
337:     }
338: 
339: 
340: 
341:     /**
342:      * {= ...}
343:      * {? ...}
344:      */
345:     public function macroExpr(MacroNode $node, $writer)
346:     {
347:         return $writer->write(($node->name === '?' ? '' : 'echo ') . '%modify(%node.args)');
348:     }
349: 
350: 
351: 
352:     /********************* run-time helpers ****************d*g**/
353: 
354: 
355: 
356:     /**
357:      * Includes subtemplate.
358:      * @param  mixed      included file name or template
359:      * @param  array      parameters
360:      * @param  Nette\Templating\ITemplate  current template
361:      * @return Nette\Templating\Template
362:      */
363:     public static function includeTemplate($destination, $params, $template)
364:     {
365:         if ($destination instanceof Nette\Templating\ITemplate) {
366:             $tpl = $destination;
367: 
368:         } elseif ($destination == NULL) { // intentionally ==
369:             throw new Nette\InvalidArgumentException("Template file name was not specified.");
370: 
371:         } else {
372:             $tpl = clone $template;
373:             if ($template instanceof Nette\Templating\IFileTemplate) {
374:                 if (substr($destination, 0, 1) !== '/' && substr($destination, 1, 1) !== ':') {
375:                     $destination = dirname($template->getFile()) . '/' . $destination;
376:                 }
377:                 $tpl->setFile($destination);
378:             }
379:         }
380: 
381:         $tpl->setParameters($params); // interface?
382:         return $tpl;
383:     }
384: 
385: 
386: 
387:     /**
388:      * Initializes local & global storage in template.
389:      * @param  Nette\Templating\ITemplate
390:      * @param  string
391:      * @return stdClass
392:      */
393:     public static function initRuntime($template, $templateId)
394:     {
395:         // local storage
396:         if (isset($template->_l)) {
397:             $local = $template->_l;
398:             unset($template->_l);
399:         } else {
400:             $local = (object) NULL;
401:         }
402:         $local->templates[$templateId] = $template;
403: 
404:         // global storage
405:         if (!isset($template->_g)) {
406:             $template->_g = (object) NULL;
407:         }
408: 
409:         return array($local, $template->_g);
410:     }
411: 
412: }
413: 
Nette Framework 2.0.0 API API documentation generated by ApiGen 2.7.0