Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.



Published on

I created a simple Smarty "How to", based on Ilia Alshanetsky (Templating & Internationalization)

Published in: Business, Technology
  • Be the first to comment


  1. 1. Smarty 9.7.8
  2. 2. Why templates? • Templates try to simplify the process of data representation by separating the business logic from the output layer. • Allows output to change without editing code logic. • Cleaner & simpler to understand code. • Greater degree of customizability. • Simultaneous development.
  3. 3. How do they work? • Templates usually consist of the logic script and a output definition identifying how the data generated by logic is to be arranged. <?php <html> $date = date(quot;Ymdquot;); <body> $name = $db->SelectVal(quot;SELECT name <h1>Welcome {NAME}!</h1> FROM users WHERE session=quot;.SID); Current Time is {DATE} </body> $tmpl = file_get_contents(quot;out.tplquot;); </html> echo str_replace(array('{DATE}', '{NAME}'), array($date,$name), $tmpl); ?>
  4. 4. Your own templating system • Task specific • Time consuming development process • Simpler • Faster • Testing • No external • Debugging dependencies • Task specific • Better code • May requires familiarity changes when new needs arise.
  5. 5. Existing solutions • Out-of-box solution • In most cases bloated • Can be used right a • “Swiss Army Knife” way approach to the problem • Relatively stable • External dependencies • Extensive feature set • Licensing issues • Internationalization • Must be available • Template layout • Many alternatives, most logic incompatible between one another. • Could be faster then “homebrew”
  6. 6. Smarty • Arguably the most known PHP based templating solution is Smarty ( • Originally developed by Andrei Zmievski • 4 years of refinement & feature improvements • Most widely available templating system • Non-restrictive Open Source license, LGPL
  7. 7. Core features • Some of the most attractive features of Smarty include: • Plug-in architecture • Built-in caching support • Conditional expression support inside templates • Evolving solution, on-going development • Reasonably well documented
  8. 8. Smarty setup • To use Smarty, up to 4 directories may be required • Template storage (templates) • Compiled template storage (templates_c) • Cached template storage (cache) **not required** • Configuration storage (configs) **not required** • Because Smarty will be writing to cache & templates_c directories, they must be writable by the web server.
  9. 9. Using Smarty // load smarty library <html> require('Smarty/Smarty.class.php'); <body> $smarty = new Smarty(); <h1>Welcome {$user}</h1> Current time is {$time} // set path of storage directories </body> $smarty->template_dir = './ </html> templates'; $smarty->compile_dir = './ templates_c'; // assign value to smarty variable $smarty->assign('name', 'John'); $smarty->assign('date', date(quot;Ymdquot;)); // load, compile and display template $smarty->display('output.tpl');
  10. 10. Smarty modifiers • One of the neat capabilities Smarty offers is the ability to apply “filtering” on the output within the templates. • This functionality allows the layout logic to reside inside the templates rather then being part of the application logic.
  11. 11. Using Smarty modifiers $smarty->assign('login', 'matija'); $smarty->assign('reg_date', 1215586447); $smarty->assign('signature', quot;-----nPHP Developernquot;); $smarty->assign('text', 'A very long an boring text'); $smarty->assign('weird', 'ineverlikedpunctuationanyway'); Name: {$login|capitalize} Date: {$reg_date|date_format:quot;%Y-%m-%dquot;} Signature: {$signature|escape|nl2br} {$text|truncate:15:quot;...quot;:true} {$weird|wordwrap:10:quot; quot;:true} Name: Matija Date: 2008-07-09 Signature: -----<br /> PHP Developer<br /> A very long ... ineverlike dpunctuati onanyway
  12. 12. Using Smarty modifiers • Smarty also provides a very convenient “default” modifier, which is particularly useful for populating forms. $smarty->assign('address', $_POST['address']); $smarty->display(quot;demo.tplquot;); <input type=quot;textquot; name=quot;addressquot; value=quot;{$address|escape|default:quot;Your addresquot;}quot; />
  13. 13. Merging templates • Smarty allows templates to reference other templates, that may be used in many places like header & footer {include file=quot;header.tplquot; val=quot;Onequot; val2=quot;Twoquot;} {include file=quot;footer.tplquot;} • Attributes specified for the include tag, will be a made available as smarty variables inside the included template.
  14. 14. Array iteration • Entire array structures can be output inside Smarty, without involving the “logic” portion of the code. $smarty->results('res', sqlite_array_query($db, quot;SELECT * FROM ...quot;)); {foreach item=row from=$res} {foreach key=column item=value from=$row} {$column}: {$value}<br /> {/foreach} {/foreach}
  15. 15. Conditional expressions {if $gender eq quot;malequot;} Welcome Sir. • Aside from the listed {elseif $gender name eq quot;femalequot;} conditional operators, Welcome Ma'am. Smarty supports all {else} Welcome, whatever you are. operators found in {/if} PHP natively {if $price > 9.99 && $price < 20.99} Daily Special! • == === != !== • {/if} > < >= <= {if count($val) > 0} {foreach item=value from=$val} ... • ! % {/if} • {/foreach} • & ~ ^
  16. 16. Capturing Output • Smarty allows the generated output for a code block to be captured in a buffer for later use. {capture name=admin_opts} {if $admin ne quot;quot;} ... {/if} {/capture} {foreach item=value from=$val} {$value} {if $smarty.capture.admin_opts ne quot;quot;} $smarty.capture.admin_opts {/if} {/foreach}
  17. 17. Smarty & JavaScript • To prevent Smarty from trying to interpret JavaScript logic, the {literal} tag can be used. {literal} <script type=quot;text/javascriptquot;> <!-- function chng_focus(phash) { window.location.hash = phash; } if (navigator.appName == quot;Microsoft Internet Explorerquot;) { window.attachEvent(quot;onloadquot;, ie_png_hack); } // --> </script> {/literal}
  18. 18. White-space cleanup • Smarty supports a {strip} tag, for removing whie- space from the generated output. {strip} <table border=0> <tr> <td> Content </td> </tr> </table> {/strip} <table border=0><tr><td>Content</td></tr></table>
  19. 19. Caching • In recognition of the fact that not all output need to be dynamic, Smarty offers a tools for caching the generated text.
  20. 20. Cache controls • Smarty caching mechanism is controlled via a series of $smarty object properties. • $cache_id - cached data storage directory • $cache_lifetime - cached data duration • $cache_handler_func - provide own cache handling mechanism (function) • $cache_modified_check - support the If- Modified-Since browser supploed header
  21. 21. Using Smarty cache • When using Smarty cache, be sure that the cache storage directory is writable by the web server. $smarty->cache_dir = './cache'; $smarty->cache_lifetime = 600; $smarty->cache_modified_check = true; $smarty->caching = true; if (!$smarty->is_cached('index.tpl')) { /* run queries, assign vars, etc... */ } $smarty->display('cache.tpl');