Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Get Smart[y]: An Interactive Presentation on th...

Get Smart[y]: An Interactive Presentation on the Smarty PHP Template Engine

Perhaps one of the handiest frameworks for PHP. Smarty allows designers to design, and programmers to program. Smarty allows you to not only create templates but also manipulate those templates with variable modifiers to handle tasks you would rather not waste time doing in your software. More so, it also enables you to cache the site, or just parts of the site for better performance.

Mark will be going through many of the features of Smarty, and show demonstrations of much of its extended functionality. Don't forget to bring your Wi-Fi enabled laptop too, because you will have the opportunity to program alongside Mark, testing what you learn during the presentation on a PHP server setup for the presentation!

Mark Stanislav

April 10, 2005
Tweet

More Decks by Mark Stanislav

Other Decks in Technology

Transcript

  1. PHP Development Server Instructions • SSH to 192.168.69.8 • Login:

    smarty • Password: sm4rty • mkdir a folder for you to use • http://192.168.69.8/~smarty/folder/ • Edit files with nano and vim
  2. Smarty is... • A presentation framework for PHP • Free

    and OSS • Very quick to learn and implement • Based on plug-ins -- make your own... • Going to make your life easier! • The only thing I felt like talking about...
  3. So why should I use it? • The big rallying

    cry is “Let the programmers program, and the designers design” • Easily create templates (“themes”) • Designers can’t really ‘break’ your main programming code -- only manipulate the data you have given them. • It has a lot of functions built-in that you will want to program -- why waste the time? • Caching will help speed up that high traffic site
  4. Sure, that sounds great... WHO USES IT? • Software http://www.drupal.org/

    (Drupal CMS) http://www.xoops.org/ (XOOPS CMS) http://www.bblog.com/ (PHP Blogging) http://www.psychostats.com/ (Game Stats) http://tikiwiki.org/ (Popular Wiki) • Web sites Anyone using the above software (http://kerneltrap.org) http://www.enotes.com (Literature Notes) http://www.foundyouonline.com (Social Networking)
  5. What we are covering in Smarty • Syntax • Variables

    • Templates • Variable modifiers • Functions • Creating a plugin • Caching
  6. Smarty Syntax • Comments: {* Look like this *} •

    Variables: {$var} or {$array[0]} or {$User.Email} • Includes: {include file=template.tpl} • If-Then-Else: {if $yes} YES {else} NO {/if} • Literals: {literal}{/literal} in case you want to display code and not have it be evaluated
  7. Folder Tree • Basically three main directories needed -templates/ (Templates)

    -templates_c/ (Templates cache) -configs/ (Template configuration files) • Configuration files are not mandatory in the context of templates, they are merely for you do define static values
  8. Variables in Smarty • Your variables are the link to

    the PHP world. Variables can hold single values in Smarty or full arrays. • You are also able to create variables within Smarty if you need something temporary. {assign var=”hotel” value=”Marriot”}
  9. Designating variable arrays <?php //Smarty framework include include 'Smarty.class.php'; //Instantiate

    Smarty $smarty = new Smarty; //Set $p_hotels array $p_hotels = array("Holiday Inn", "Marriot", “Motel Thirty-Eight”); //Set {$s_hotels} in Smarty to $p_hotels $smarty->assign('s_hotels', $p_hotels); //Call our template $smarty->display('example-one.tpl'); ?>
  10. Reserved Smarty Variables • $smarty.* is a reserved variable tree

    $smarty.cookies.hotel = “hotel” Cookie $smarty.request.hotel = Get index.php?hotel= value $smarty.post.hotel = Get value of POST variable hotel $smarty.session.id = Retrieve PHP session ID $smarty.section.hotel.total = Total of items in array • Here is our first demo of smarty... http://127.0.0.1/example-one.php
  11. Using {section} & array items • Call each array valuable

    the “boring way” Array value 0: {$s_hotels[0]} Array value 1: {$s_hotels[1]} • To loop through an array, you can use {section}{/section} {section name=hotel loop=$s_hotels} {$s_hotels[hotel]} {/section} • Other interesting uses of {section} are... {$smarty.section.hotels.total} {$smarty.section.hotels.rownum} {section} blah {sectionelse} No hotels! {/section} {$smarty.section.hotels.index}
  12. Configuration Files • Configuration files will allow you to define

    variables for ease • Example from configs/hotels.conf: 1. [Hotels] 2. expensive = “very much so” • This will now allow you to call these variables when you include the config {config_load file=”hotels.conf” section=Hotels} Expensive?: {#expensive#} Expensive?: {$smarty.config.expensive} Expensive?: “very much so” (same result for both)
  13. Mid-Presentation Security Note • Smarty does allow the embedding of

    PHP code within the template if the security features are turned off. You will, of course, want to try and never implement it and shouldn’t need to (that I can forsee).
  14. Smarty Templates • .tpl is the standard file extension for

    templates in Smarty • The data assigned to your instance of Smarty is now able to be used constructively within the template • The template has built-in variable modifiers Truncate text Indent text Strip tags Word wrap String replacement Capitalize Date formatting Count characters
  15. Variable Modifiers, EX. 1 • Truncate {$blog_entry|truncate:210} -This will truncate

    at 210th character but also end at the end of a word (so as to not cut off anythi {$blog_entry|truncate:10:”...”} -This will cause it to end with an ellipsis so you can entice your readers about your trip to Ohio... -If you add :true to the end of the modifier statement, you will truncate at the exact character.
  16. Variable Modifiers, EX. 2 • strip_tags {$blog_content|strip_tags:false} -This will take

    your given content, remove any HTML tags and replace the stripped tags without including a space Before: <font color=”red”>Hi NOTACON</font> After: Hi NOTACON -Smarty essentially removes anything with < >
  17. Variable Modifiers, EX. 3 • wordwrap {$blog_content|wordwrap:10:"\n"} -This will wrap

    on the word nearest to the 10th character. It will wrap using a new-line. -If you add :true to the end of the statement, it will wrap at the exact character like our truncate variable modifier
  18. Notes on Variable Modifiers • You can combine any number

    of them using pipes • You can combine them with Smarty functions also, ex (from Smarty Docs): {html_table loop=$myvar|truncate:40:"..."}
  19. Smarty Functions • html_table {html_table loop=$data cols=4 table_attr='border="0"'} -Easily create

    tables with every attribute you want, consult documentation to see all the aspects. -In this example we loop through an array of data, and we loop after the fourth column to a new row. Obviously this assigns the border to a width of 0 -This is a lot cleaner then making your own loops to deal with tablizing (sure it’s a word) data
  20. More on Smarty Functions • html_options -Imagine we have two

    arrays. One array has values [1-3] and the other has the hotel names we defined earlier. <select name=hotels> {html_options values=$hotels_ids output=$hotels} </select> -Our output on the web site [one row] looks like.. <select name=hotels> <option label=”Marriot” value=”2”>Marriot</option> </select>
  21. Quick Functions • counter {counter start=0 skip=2} • mailto {mailto

    address="[email protected]" subject="NOTACON"} • fetch {fetch file="http://www.goodstuff.com/news.txt"}
  22. The really useful function • Cycle -Ever want to alternate

    between colors for rows of a table... easily? <table> {section name=rows loop=$your_data} <tr bgcolor="{cycle values="#000000,#EFEFEF"}"> <td>{$your_data[rows]}</td> </tr> {/section} </table>
  23. Random “Advanced” Stuff • Pre-Filters: Remove those unwanted comments from

    templates before they are compiled. • Post-Filters: Add those unwanted (but cooler) comments to templates following compilation. • Output-Filters: Replace your user-friendly tags with HTML that actually does something.
  24. Creating a Q&D Plugin <?php function smarty_outputfilter_tags($source, $smarty) { //Find

    code tags and replace them with the needed HTML $source = str_replace("[code]", "<pre><code>", $source); $source = str_replace("[/code]", "</code></pre>", $source); return $source; } ?> Example of a Smarty Plugin: How to call plugin... $smarty->load_filter('output','tags'); $smarty->display('your_page.tpl');
  25. Template Caching • You are able to cache the entire

    page or just a single section • Example: You query your news database each time someone visits the site. Instead of this, cache the news page and show that static page to the people. Set the refresh for whatever you wish • Basic aspects to caching are - $smarty->caching = {0,1,2} - $smarty->cache_lifetime = # of seconds; - $smarty->clear_cache('file.tpl');
  26. Obligatory Thank You Slide... • Apple for making my Powerbook

    and Keynote 2 • http://smarty.php.net for actually posting that I was speaking here and creating Smarty • Joe Stump (www.joestump.net) for enlightening me • My fellow Core staff (and our brave volunteers) • Kathleen Sulewski, Kim Dubicki, Jeff England, Matt Fanto, Jeff Peckham, Ken West, Citadel, Corey Houston, James Turner and anyone else who sat through this.