• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content




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

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



Total Views
Views on SlideShare
Embed Views



3 Embeds 13

http://www.slideshare.net 11
http://www.linkedin.com 1
https://www.linkedin.com 1



Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
Post Comment
Edit your comment

    Smarty Smarty Presentation Transcript

    • Smarty 9.7.8
    • 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.
    • 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); ?>
    • 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.
    • 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”
    • Smarty • Arguably the most known PHP based templating solution is Smarty (smarty.net) • Originally developed by Andrei Zmievski • 4 years of refinement & feature improvements • Most widely available templating system • Non-restrictive Open Source license, LGPL
    • 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
    • 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.
    • 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');
    • 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.
    • 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
    • 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; />
    • 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.
    • 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}
    • 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} • & ~ ^
    • 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}
    • 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}
    • 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>
    • Caching • In recognition of the fact that not all output need to be dynamic, Smarty offers a tools for caching the generated text.
    • 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
    • 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');