Packages

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