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.

Get Smart[y]: The Smarty Template Engine for PHP


Published on

Published in: Technology
  • Be the first to comment

  • Be the first to like this

Get Smart[y]: The Smarty Template Engine for PHP

  1. 1. Get Smart[y]An Interactive Presentation on the Smarty PHP Template Engine
  2. 2. PHP Development Server Instructions• SSH to• Login: smarty• Password: sm4rty• mkdir a folder for you to use•• Edit files with nano and vim
  3. 3. 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...
  4. 4. 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
  5. 5. Sure, that sounds great... WHO USES IT?• Software (Drupal CMS) (XOOPS CMS) (PHP Blogging) (Game Stats) (Popular Wiki)• Web sites Anyone using the above software ( (Literature Notes) (Social Networking)
  6. 6. What we are covering in Smarty• Syntax• Variables• Templates• Variable modifiers• Functions• Creating a plugin• Caching
  7. 7. 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
  8. 8. 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
  9. 9. 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”}
  10. 10. Designating variable arrays<?php//Smarty framework includeinclude 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);?>
  11. 11. Reserved Smarty Variables• $smarty.* is a reserved variable tree $smarty.cookies.hotel = “hotel” Cookie $smarty.request.hotel = Get index.php?hotel= value $ = Get value of POST variable hotel $ = Retrieve PHP session ID $ = Total of items in array• Here is our first demo of smarty...
  12. 12. 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... {$} {$} {section} blah {sectionelse} No hotels! {/section} {$}
  13. 13. 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)
  14. 14. 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).
  15. 15. 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 Indent text Strip tags Word wrap text String Date Count Capitalizereplacement formatting characters
  16. 16. 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.
  17. 17. 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 < >
  18. 18. 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
  19. 19. 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:"..."}
  20. 20. 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
  21. 21. 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>
  22. 22. Quick Functions• counter {counter start=0 skip=2}• mailto {mailto address="" subject="NOTACON"}• fetch {fetch file=""}
  23. 23. 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>
  24. 24. 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.
  25. 25. Creating a Q&D PluginExample of a Smarty Plugin:<?phpfunction 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;}?>How to call plugin... $smarty->load_filter(output,tags); $smarty->display(your_page.tpl);
  26. 26. 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);
  27. 27. Obligatory Thank You Slide...• Apple for making my Powerbook and Keynote 2• for actually posting that I was speaking here and creating Smarty• Joe Stump ( 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.
  28. 28. References••• Random Googling...