SlideShare une entreprise Scribd logo
1  sur  21
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');

Contenu connexe

Tendances

PHP security audits
PHP security auditsPHP security audits
PHP security auditsDamien Seguy
 
Marrow: A Meta-Framework for Python 2.6+ and 3.1+
Marrow: A Meta-Framework for Python 2.6+ and 3.1+Marrow: A Meta-Framework for Python 2.6+ and 3.1+
Marrow: A Meta-Framework for Python 2.6+ and 3.1+ConFoo
 
Let's write secure Drupal code! - DrupalCamp London 2019
Let's write secure Drupal code! - DrupalCamp London 2019Let's write secure Drupal code! - DrupalCamp London 2019
Let's write secure Drupal code! - DrupalCamp London 2019Balázs Tatár
 
Geek Moot '09 -- Smarty 101
Geek Moot '09 -- Smarty 101Geek Moot '09 -- Smarty 101
Geek Moot '09 -- Smarty 101Ted Kulp
 
Jquery presentation
Jquery presentationJquery presentation
Jquery presentationguest5d87aa6
 
Forget about Index.php and build you applications around HTTP - PHPers Cracow
Forget about Index.php and build you applications around HTTP - PHPers CracowForget about Index.php and build you applications around HTTP - PHPers Cracow
Forget about Index.php and build you applications around HTTP - PHPers CracowKacper Gunia
 
Система рендеринга в Magento
Система рендеринга в MagentoСистема рендеринга в Magento
Система рендеринга в MagentoMagecom Ukraine
 
Clear php reference
Clear php referenceClear php reference
Clear php referenceDamien Seguy
 
PhpSpec 2.0 ilustrated by examples
PhpSpec 2.0 ilustrated by examplesPhpSpec 2.0 ilustrated by examples
PhpSpec 2.0 ilustrated by examplesMarcello Duarte
 
Introduction to PHP Lecture 1
Introduction to PHP Lecture 1Introduction to PHP Lecture 1
Introduction to PHP Lecture 1Ajay Khatri
 
Basics of Java Script (JS)
Basics of Java Script (JS)Basics of Java Script (JS)
Basics of Java Script (JS)Ajay Khatri
 
Speed up your developments with Symfony2
Speed up your developments with Symfony2Speed up your developments with Symfony2
Speed up your developments with Symfony2Hugo Hamon
 
Top 10 php classic traps php serbia
Top 10 php classic traps php serbiaTop 10 php classic traps php serbia
Top 10 php classic traps php serbiaDamien Seguy
 
My app is secure... I think
My app is secure... I thinkMy app is secure... I think
My app is secure... I thinkWim Godden
 
November Camp - Spec BDD with PHPSpec 2
November Camp - Spec BDD with PHPSpec 2November Camp - Spec BDD with PHPSpec 2
November Camp - Spec BDD with PHPSpec 2Kacper Gunia
 

Tendances (20)

PHP security audits
PHP security auditsPHP security audits
PHP security audits
 
Marrow: A Meta-Framework for Python 2.6+ and 3.1+
Marrow: A Meta-Framework for Python 2.6+ and 3.1+Marrow: A Meta-Framework for Python 2.6+ and 3.1+
Marrow: A Meta-Framework for Python 2.6+ and 3.1+
 
WCLV13 JavaScript
WCLV13 JavaScriptWCLV13 JavaScript
WCLV13 JavaScript
 
Let's write secure Drupal code! - DrupalCamp London 2019
Let's write secure Drupal code! - DrupalCamp London 2019Let's write secure Drupal code! - DrupalCamp London 2019
Let's write secure Drupal code! - DrupalCamp London 2019
 
Geek Moot '09 -- Smarty 101
Geek Moot '09 -- Smarty 101Geek Moot '09 -- Smarty 101
Geek Moot '09 -- Smarty 101
 
Hooks WCSD12
Hooks WCSD12Hooks WCSD12
Hooks WCSD12
 
Jquery presentation
Jquery presentationJquery presentation
Jquery presentation
 
Forget about Index.php and build you applications around HTTP - PHPers Cracow
Forget about Index.php and build you applications around HTTP - PHPers CracowForget about Index.php and build you applications around HTTP - PHPers Cracow
Forget about Index.php and build you applications around HTTP - PHPers Cracow
 
PHP Security
PHP SecurityPHP Security
PHP Security
 
Система рендеринга в Magento
Система рендеринга в MagentoСистема рендеринга в Magento
Система рендеринга в Magento
 
Clear php reference
Clear php referenceClear php reference
Clear php reference
 
PhpSpec 2.0 ilustrated by examples
PhpSpec 2.0 ilustrated by examplesPhpSpec 2.0 ilustrated by examples
PhpSpec 2.0 ilustrated by examples
 
Introduction to PHP Lecture 1
Introduction to PHP Lecture 1Introduction to PHP Lecture 1
Introduction to PHP Lecture 1
 
Basics of Java Script (JS)
Basics of Java Script (JS)Basics of Java Script (JS)
Basics of Java Script (JS)
 
Speed up your developments with Symfony2
Speed up your developments with Symfony2Speed up your developments with Symfony2
Speed up your developments with Symfony2
 
Xmpp prebind
Xmpp prebindXmpp prebind
Xmpp prebind
 
Top 10 php classic traps php serbia
Top 10 php classic traps php serbiaTop 10 php classic traps php serbia
Top 10 php classic traps php serbia
 
My app is secure... I think
My app is secure... I thinkMy app is secure... I think
My app is secure... I think
 
jQuery PPT
jQuery PPTjQuery PPT
jQuery PPT
 
November Camp - Spec BDD with PHPSpec 2
November Camp - Spec BDD with PHPSpec 2November Camp - Spec BDD with PHPSpec 2
November Camp - Spec BDD with PHPSpec 2
 

Similaire à Smarty

JUDCon London 2011 - Bin packing with drools planner by example
JUDCon London 2011 - Bin packing with drools planner by exampleJUDCon London 2011 - Bin packing with drools planner by example
JUDCon London 2011 - Bin packing with drools planner by exampleGeoffrey De Smet
 
Introduction to CodeIgniter (RefreshAugusta, 20 May 2009)
Introduction to CodeIgniter (RefreshAugusta, 20 May 2009)Introduction to CodeIgniter (RefreshAugusta, 20 May 2009)
Introduction to CodeIgniter (RefreshAugusta, 20 May 2009)Michael Wales
 
How to learn to build your own PHP framework
How to learn to build your own PHP frameworkHow to learn to build your own PHP framework
How to learn to build your own PHP frameworkDinh Pham
 
Hanoi php day 2008 - 01.pham cong dinh - how.to.build.your.own.framework
Hanoi php day 2008 - 01.pham cong dinh - how.to.build.your.own.frameworkHanoi php day 2008 - 01.pham cong dinh - how.to.build.your.own.framework
Hanoi php day 2008 - 01.pham cong dinh - how.to.build.your.own.frameworkNguyen Duc Phu
 
More Secrets of JavaScript Libraries
More Secrets of JavaScript LibrariesMore Secrets of JavaScript Libraries
More Secrets of JavaScript Librariesjeresig
 
Using Geeklog as a Web Application Framework
Using Geeklog as a Web Application FrameworkUsing Geeklog as a Web Application Framework
Using Geeklog as a Web Application FrameworkDirk Haun
 
What's new in Rails 2?
What's new in Rails 2?What's new in Rails 2?
What's new in Rails 2?brynary
 
Impacta - Show Day de Rails
Impacta - Show Day de RailsImpacta - Show Day de Rails
Impacta - Show Day de RailsFabio Akita
 
PSGI and Plack from first principles
PSGI and Plack from first principlesPSGI and Plack from first principles
PSGI and Plack from first principlesPerl Careers
 
Exploiting the newer perl to improve your plugins
Exploiting the newer perl to improve your pluginsExploiting the newer perl to improve your plugins
Exploiting the newer perl to improve your pluginsMarian Marinov
 
Bubbles & Trees with jQuery
Bubbles & Trees with jQueryBubbles & Trees with jQuery
Bubbles & Trees with jQueryBastian Feder
 
jQuery from the very beginning
jQuery from the very beginningjQuery from the very beginning
jQuery from the very beginningAnis Ahmad
 
PHP Presentation
PHP PresentationPHP Presentation
PHP PresentationAnkush Jain
 
Django - Framework web para perfeccionistas com prazos
Django - Framework web para perfeccionistas com prazosDjango - Framework web para perfeccionistas com prazos
Django - Framework web para perfeccionistas com prazosIgor Sobreira
 
Systems Automation with Puppet
Systems Automation with PuppetSystems Automation with Puppet
Systems Automation with Puppetelliando dias
 

Similaire à Smarty (20)

JUDCon London 2011 - Bin packing with drools planner by example
JUDCon London 2011 - Bin packing with drools planner by exampleJUDCon London 2011 - Bin packing with drools planner by example
JUDCon London 2011 - Bin packing with drools planner by example
 
Symfony 1, mi viejo amigo
Symfony 1, mi viejo amigoSymfony 1, mi viejo amigo
Symfony 1, mi viejo amigo
 
Introduction to CodeIgniter (RefreshAugusta, 20 May 2009)
Introduction to CodeIgniter (RefreshAugusta, 20 May 2009)Introduction to CodeIgniter (RefreshAugusta, 20 May 2009)
Introduction to CodeIgniter (RefreshAugusta, 20 May 2009)
 
How to learn to build your own PHP framework
How to learn to build your own PHP frameworkHow to learn to build your own PHP framework
How to learn to build your own PHP framework
 
Hanoi php day 2008 - 01.pham cong dinh - how.to.build.your.own.framework
Hanoi php day 2008 - 01.pham cong dinh - how.to.build.your.own.frameworkHanoi php day 2008 - 01.pham cong dinh - how.to.build.your.own.framework
Hanoi php day 2008 - 01.pham cong dinh - how.to.build.your.own.framework
 
Satchmo
SatchmoSatchmo
Satchmo
 
Seam Glassfish Slidecast
Seam Glassfish SlidecastSeam Glassfish Slidecast
Seam Glassfish Slidecast
 
More Secrets of JavaScript Libraries
More Secrets of JavaScript LibrariesMore Secrets of JavaScript Libraries
More Secrets of JavaScript Libraries
 
Using Geeklog as a Web Application Framework
Using Geeklog as a Web Application FrameworkUsing Geeklog as a Web Application Framework
Using Geeklog as a Web Application Framework
 
Modern Perl
Modern PerlModern Perl
Modern Perl
 
What's new in Rails 2?
What's new in Rails 2?What's new in Rails 2?
What's new in Rails 2?
 
Impacta - Show Day de Rails
Impacta - Show Day de RailsImpacta - Show Day de Rails
Impacta - Show Day de Rails
 
PSGI and Plack from first principles
PSGI and Plack from first principlesPSGI and Plack from first principles
PSGI and Plack from first principles
 
Exploiting the newer perl to improve your plugins
Exploiting the newer perl to improve your pluginsExploiting the newer perl to improve your plugins
Exploiting the newer perl to improve your plugins
 
Bubbles & Trees with jQuery
Bubbles & Trees with jQueryBubbles & Trees with jQuery
Bubbles & Trees with jQuery
 
jQuery from the very beginning
jQuery from the very beginningjQuery from the very beginning
jQuery from the very beginning
 
PHP Presentation
PHP PresentationPHP Presentation
PHP Presentation
 
Django - Framework web para perfeccionistas com prazos
Django - Framework web para perfeccionistas com prazosDjango - Framework web para perfeccionistas com prazos
Django - Framework web para perfeccionistas com prazos
 
Sinatra
SinatraSinatra
Sinatra
 
Systems Automation with Puppet
Systems Automation with PuppetSystems Automation with Puppet
Systems Automation with Puppet
 

Dernier

Call Girls Hebbal Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
Call Girls Hebbal Just Call 👗 7737669865 👗 Top Class Call Girl Service BangaloreCall Girls Hebbal Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
Call Girls Hebbal Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangaloreamitlee9823
 
Al Mizhar Dubai Escorts +971561403006 Escorts Service In Al Mizhar
Al Mizhar Dubai Escorts +971561403006 Escorts Service In Al MizharAl Mizhar Dubai Escorts +971561403006 Escorts Service In Al Mizhar
Al Mizhar Dubai Escorts +971561403006 Escorts Service In Al Mizharallensay1
 
BAGALUR CALL GIRL IN 98274*61493 ❤CALL GIRLS IN ESCORT SERVICE❤CALL GIRL
BAGALUR CALL GIRL IN 98274*61493 ❤CALL GIRLS IN ESCORT SERVICE❤CALL GIRLBAGALUR CALL GIRL IN 98274*61493 ❤CALL GIRLS IN ESCORT SERVICE❤CALL GIRL
BAGALUR CALL GIRL IN 98274*61493 ❤CALL GIRLS IN ESCORT SERVICE❤CALL GIRLkapoorjyoti4444
 
Nelamangala Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...
Nelamangala Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...Nelamangala Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...
Nelamangala Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...amitlee9823
 
Value Proposition canvas- Customer needs and pains
Value Proposition canvas- Customer needs and painsValue Proposition canvas- Customer needs and pains
Value Proposition canvas- Customer needs and painsP&CO
 
Malegaon Call Girls Service ☎ ️82500–77686 ☎️ Enjoy 24/7 Escort Service
Malegaon Call Girls Service ☎ ️82500–77686 ☎️ Enjoy 24/7 Escort ServiceMalegaon Call Girls Service ☎ ️82500–77686 ☎️ Enjoy 24/7 Escort Service
Malegaon Call Girls Service ☎ ️82500–77686 ☎️ Enjoy 24/7 Escort ServiceDamini Dixit
 
SEO Case Study: How I Increased SEO Traffic & Ranking by 50-60% in 6 Months
SEO Case Study: How I Increased SEO Traffic & Ranking by 50-60%  in 6 MonthsSEO Case Study: How I Increased SEO Traffic & Ranking by 50-60%  in 6 Months
SEO Case Study: How I Increased SEO Traffic & Ranking by 50-60% in 6 MonthsIndeedSEO
 
Call Girls Zirakpur👧 Book Now📱7837612180 📞👉Call Girl Service In Zirakpur No A...
Call Girls Zirakpur👧 Book Now📱7837612180 📞👉Call Girl Service In Zirakpur No A...Call Girls Zirakpur👧 Book Now📱7837612180 📞👉Call Girl Service In Zirakpur No A...
Call Girls Zirakpur👧 Book Now📱7837612180 📞👉Call Girl Service In Zirakpur No A...Sheetaleventcompany
 
Eluru Call Girls Service ☎ ️93326-06886 ❤️‍🔥 Enjoy 24/7 Escort Service
Eluru Call Girls Service ☎ ️93326-06886 ❤️‍🔥 Enjoy 24/7 Escort ServiceEluru Call Girls Service ☎ ️93326-06886 ❤️‍🔥 Enjoy 24/7 Escort Service
Eluru Call Girls Service ☎ ️93326-06886 ❤️‍🔥 Enjoy 24/7 Escort ServiceDamini Dixit
 
How to Get Started in Social Media for Art League City
How to Get Started in Social Media for Art League CityHow to Get Started in Social Media for Art League City
How to Get Started in Social Media for Art League CityEric T. Tung
 
Cracking the Cultural Competence Code.pptx
Cracking the Cultural Competence Code.pptxCracking the Cultural Competence Code.pptx
Cracking the Cultural Competence Code.pptxWorkforce Group
 
Call Girls Service In Old Town Dubai ((0551707352)) Old Town Dubai Call Girl ...
Call Girls Service In Old Town Dubai ((0551707352)) Old Town Dubai Call Girl ...Call Girls Service In Old Town Dubai ((0551707352)) Old Town Dubai Call Girl ...
Call Girls Service In Old Town Dubai ((0551707352)) Old Town Dubai Call Girl ...allensay1
 
FULL ENJOY Call Girls In Majnu Ka Tilla, Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Majnu Ka Tilla, Delhi Contact Us 8377877756FULL ENJOY Call Girls In Majnu Ka Tilla, Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Majnu Ka Tilla, Delhi Contact Us 8377877756dollysharma2066
 
Call Girls In Nangloi Rly Metro ꧂…….95996 … 13876 Enjoy ꧂Escort
Call Girls In Nangloi Rly Metro ꧂…….95996 … 13876 Enjoy ꧂EscortCall Girls In Nangloi Rly Metro ꧂…….95996 … 13876 Enjoy ꧂Escort
Call Girls In Nangloi Rly Metro ꧂…….95996 … 13876 Enjoy ꧂Escortdlhescort
 
Quick Doctor In Kuwait +2773`7758`557 Kuwait Doha Qatar Dubai Abu Dhabi Sharj...
Quick Doctor In Kuwait +2773`7758`557 Kuwait Doha Qatar Dubai Abu Dhabi Sharj...Quick Doctor In Kuwait +2773`7758`557 Kuwait Doha Qatar Dubai Abu Dhabi Sharj...
Quick Doctor In Kuwait +2773`7758`557 Kuwait Doha Qatar Dubai Abu Dhabi Sharj...daisycvs
 
Call Girls From Raj Nagar Extension Ghaziabad❤️8448577510 ⊹Best Escorts Servi...
Call Girls From Raj Nagar Extension Ghaziabad❤️8448577510 ⊹Best Escorts Servi...Call Girls From Raj Nagar Extension Ghaziabad❤️8448577510 ⊹Best Escorts Servi...
Call Girls From Raj Nagar Extension Ghaziabad❤️8448577510 ⊹Best Escorts Servi...lizamodels9
 
Russian Call Girls In Rajiv Chowk Gurgaon ❤️8448577510 ⊹Best Escorts Service ...
Russian Call Girls In Rajiv Chowk Gurgaon ❤️8448577510 ⊹Best Escorts Service ...Russian Call Girls In Rajiv Chowk Gurgaon ❤️8448577510 ⊹Best Escorts Service ...
Russian Call Girls In Rajiv Chowk Gurgaon ❤️8448577510 ⊹Best Escorts Service ...lizamodels9
 
Call Girls In Noida 959961⊹3876 Independent Escort Service Noida
Call Girls In Noida 959961⊹3876 Independent Escort Service NoidaCall Girls In Noida 959961⊹3876 Independent Escort Service Noida
Call Girls In Noida 959961⊹3876 Independent Escort Service Noidadlhescort
 
Chandigarh Escorts Service 📞8868886958📞 Just📲 Call Nihal Chandigarh Call Girl...
Chandigarh Escorts Service 📞8868886958📞 Just📲 Call Nihal Chandigarh Call Girl...Chandigarh Escorts Service 📞8868886958📞 Just📲 Call Nihal Chandigarh Call Girl...
Chandigarh Escorts Service 📞8868886958📞 Just📲 Call Nihal Chandigarh Call Girl...Sheetaleventcompany
 

Dernier (20)

Call Girls Hebbal Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
Call Girls Hebbal Just Call 👗 7737669865 👗 Top Class Call Girl Service BangaloreCall Girls Hebbal Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
Call Girls Hebbal Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
 
Al Mizhar Dubai Escorts +971561403006 Escorts Service In Al Mizhar
Al Mizhar Dubai Escorts +971561403006 Escorts Service In Al MizharAl Mizhar Dubai Escorts +971561403006 Escorts Service In Al Mizhar
Al Mizhar Dubai Escorts +971561403006 Escorts Service In Al Mizhar
 
BAGALUR CALL GIRL IN 98274*61493 ❤CALL GIRLS IN ESCORT SERVICE❤CALL GIRL
BAGALUR CALL GIRL IN 98274*61493 ❤CALL GIRLS IN ESCORT SERVICE❤CALL GIRLBAGALUR CALL GIRL IN 98274*61493 ❤CALL GIRLS IN ESCORT SERVICE❤CALL GIRL
BAGALUR CALL GIRL IN 98274*61493 ❤CALL GIRLS IN ESCORT SERVICE❤CALL GIRL
 
(Anamika) VIP Call Girls Napur Call Now 8617697112 Napur Escorts 24x7
(Anamika) VIP Call Girls Napur Call Now 8617697112 Napur Escorts 24x7(Anamika) VIP Call Girls Napur Call Now 8617697112 Napur Escorts 24x7
(Anamika) VIP Call Girls Napur Call Now 8617697112 Napur Escorts 24x7
 
Nelamangala Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...
Nelamangala Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...Nelamangala Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...
Nelamangala Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...
 
Value Proposition canvas- Customer needs and pains
Value Proposition canvas- Customer needs and painsValue Proposition canvas- Customer needs and pains
Value Proposition canvas- Customer needs and pains
 
Malegaon Call Girls Service ☎ ️82500–77686 ☎️ Enjoy 24/7 Escort Service
Malegaon Call Girls Service ☎ ️82500–77686 ☎️ Enjoy 24/7 Escort ServiceMalegaon Call Girls Service ☎ ️82500–77686 ☎️ Enjoy 24/7 Escort Service
Malegaon Call Girls Service ☎ ️82500–77686 ☎️ Enjoy 24/7 Escort Service
 
SEO Case Study: How I Increased SEO Traffic & Ranking by 50-60% in 6 Months
SEO Case Study: How I Increased SEO Traffic & Ranking by 50-60%  in 6 MonthsSEO Case Study: How I Increased SEO Traffic & Ranking by 50-60%  in 6 Months
SEO Case Study: How I Increased SEO Traffic & Ranking by 50-60% in 6 Months
 
Call Girls Zirakpur👧 Book Now📱7837612180 📞👉Call Girl Service In Zirakpur No A...
Call Girls Zirakpur👧 Book Now📱7837612180 📞👉Call Girl Service In Zirakpur No A...Call Girls Zirakpur👧 Book Now📱7837612180 📞👉Call Girl Service In Zirakpur No A...
Call Girls Zirakpur👧 Book Now📱7837612180 📞👉Call Girl Service In Zirakpur No A...
 
Eluru Call Girls Service ☎ ️93326-06886 ❤️‍🔥 Enjoy 24/7 Escort Service
Eluru Call Girls Service ☎ ️93326-06886 ❤️‍🔥 Enjoy 24/7 Escort ServiceEluru Call Girls Service ☎ ️93326-06886 ❤️‍🔥 Enjoy 24/7 Escort Service
Eluru Call Girls Service ☎ ️93326-06886 ❤️‍🔥 Enjoy 24/7 Escort Service
 
How to Get Started in Social Media for Art League City
How to Get Started in Social Media for Art League CityHow to Get Started in Social Media for Art League City
How to Get Started in Social Media for Art League City
 
Cracking the Cultural Competence Code.pptx
Cracking the Cultural Competence Code.pptxCracking the Cultural Competence Code.pptx
Cracking the Cultural Competence Code.pptx
 
Call Girls Service In Old Town Dubai ((0551707352)) Old Town Dubai Call Girl ...
Call Girls Service In Old Town Dubai ((0551707352)) Old Town Dubai Call Girl ...Call Girls Service In Old Town Dubai ((0551707352)) Old Town Dubai Call Girl ...
Call Girls Service In Old Town Dubai ((0551707352)) Old Town Dubai Call Girl ...
 
FULL ENJOY Call Girls In Majnu Ka Tilla, Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Majnu Ka Tilla, Delhi Contact Us 8377877756FULL ENJOY Call Girls In Majnu Ka Tilla, Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Majnu Ka Tilla, Delhi Contact Us 8377877756
 
Call Girls In Nangloi Rly Metro ꧂…….95996 … 13876 Enjoy ꧂Escort
Call Girls In Nangloi Rly Metro ꧂…….95996 … 13876 Enjoy ꧂EscortCall Girls In Nangloi Rly Metro ꧂…….95996 … 13876 Enjoy ꧂Escort
Call Girls In Nangloi Rly Metro ꧂…….95996 … 13876 Enjoy ꧂Escort
 
Quick Doctor In Kuwait +2773`7758`557 Kuwait Doha Qatar Dubai Abu Dhabi Sharj...
Quick Doctor In Kuwait +2773`7758`557 Kuwait Doha Qatar Dubai Abu Dhabi Sharj...Quick Doctor In Kuwait +2773`7758`557 Kuwait Doha Qatar Dubai Abu Dhabi Sharj...
Quick Doctor In Kuwait +2773`7758`557 Kuwait Doha Qatar Dubai Abu Dhabi Sharj...
 
Call Girls From Raj Nagar Extension Ghaziabad❤️8448577510 ⊹Best Escorts Servi...
Call Girls From Raj Nagar Extension Ghaziabad❤️8448577510 ⊹Best Escorts Servi...Call Girls From Raj Nagar Extension Ghaziabad❤️8448577510 ⊹Best Escorts Servi...
Call Girls From Raj Nagar Extension Ghaziabad❤️8448577510 ⊹Best Escorts Servi...
 
Russian Call Girls In Rajiv Chowk Gurgaon ❤️8448577510 ⊹Best Escorts Service ...
Russian Call Girls In Rajiv Chowk Gurgaon ❤️8448577510 ⊹Best Escorts Service ...Russian Call Girls In Rajiv Chowk Gurgaon ❤️8448577510 ⊹Best Escorts Service ...
Russian Call Girls In Rajiv Chowk Gurgaon ❤️8448577510 ⊹Best Escorts Service ...
 
Call Girls In Noida 959961⊹3876 Independent Escort Service Noida
Call Girls In Noida 959961⊹3876 Independent Escort Service NoidaCall Girls In Noida 959961⊹3876 Independent Escort Service Noida
Call Girls In Noida 959961⊹3876 Independent Escort Service Noida
 
Chandigarh Escorts Service 📞8868886958📞 Just📲 Call Nihal Chandigarh Call Girl...
Chandigarh Escorts Service 📞8868886958📞 Just📲 Call Nihal Chandigarh Call Girl...Chandigarh Escorts Service 📞8868886958📞 Just📲 Call Nihal Chandigarh Call Girl...
Chandigarh Escorts Service 📞8868886958📞 Just📲 Call Nihal Chandigarh Call Girl...
 

Smarty

  • 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. 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. 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. 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. 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
  • 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. Caching • In recognition of the fact that not all output need to be dynamic, Smarty offers a tools for caching the generated text.
  • 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. 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');