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

7,922 views

Published on

Published in: Technology
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
7,922
On SlideShare
0
From Embeds
0
Number of Embeds
3
Actions
Shares
0
Downloads
75
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide
  • Some things I want to point out....\n-There will be very few (1) actual example of Smarty in action, this is because Smarty is a presentation layer and I am not presenting how to design web sites.\n-The presentation will show the parts to make the whole, I am merely laying out what it does and why you may want to use it. Hopefully, you will take enough away from the presentation to see the usefulness of the project.\n-Also, I am not a developer of this project and don’t even know who is. I am an end-user that has implemented this in software and have spoken to many others who also have.\n-It will be very important to remember during the presentation that this won’t apply to everyones methods or uses of PHP and web design/creation. Some stuff seems redundant in it’s implementation, but really, it is all necessary for correct integration of Smarty\n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • Pre: Template prefilters are PHP functions that your templates are ran through before they are compiled. This is good for preprocessing your templates to remove unwanted comments, keeping an eye on what people are putting in their templates, etc.\n\nPost: Template postfilters are PHP functions that your templates are ran through after they are compiled.\n\nOutput: This differs from postfilters because postfilters operate on compiled templates before they are saved to the disk, and output filters operate on the template output when it is executed.\n
  • \n
  • 0 is disabled\n1 is enabled\n2 is multi-cache, where you can have caching on each individual template\n\nCache groups allow you to basically plow through entire directories of caches. Remember this is all a directory structure so you could clear all cache files for files in an entire directory at a time.\n
  • \n
  • \n
  • Get Smart[y]: The Smarty Template Engine for PHP

    1. 1. Get Smart[y]An Interactive Presentation on the Smarty PHP Template Engine mstanisl@emich.edu
    2. 2. 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
    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 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)
    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 $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
    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... {$smarty.section.hotels.total} {$smarty.section.hotels.rownum} {section} blah {sectionelse} No hotels! {/section} {$smarty.section.hotels.index}
    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="n@c.com" subject="NOTACON"}• fetch {fetch file="http://www.goodstuff.com/news.txt"}
    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• 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.
    28. 28. References• http://smarty.php.net/manual/en/• http://zend.com/zend/tut/tutorial-stump.php• Random Googling...

    ×