SlideShare uma empresa Scribd logo
1 de 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');

Mais conteúdo relacionado

Mais procurados

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
 

Mais procurados (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
 

Semelhante a 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
 

Semelhante a 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
 

Último

Innovation Conference 5th March 2024.pdf
Innovation Conference 5th March 2024.pdfInnovation Conference 5th March 2024.pdf
Innovation Conference 5th March 2024.pdfrichard876048
 
Memorándum de Entendimiento (MoU) entre Codelco y SQM
Memorándum de Entendimiento (MoU) entre Codelco y SQMMemorándum de Entendimiento (MoU) entre Codelco y SQM
Memorándum de Entendimiento (MoU) entre Codelco y SQMVoces Mineras
 
NewBase 19 April 2024 Energy News issue - 1717 by Khaled Al Awadi.pdf
NewBase  19 April  2024  Energy News issue - 1717 by Khaled Al Awadi.pdfNewBase  19 April  2024  Energy News issue - 1717 by Khaled Al Awadi.pdf
NewBase 19 April 2024 Energy News issue - 1717 by Khaled Al Awadi.pdfKhaled Al Awadi
 
Investment in The Coconut Industry by Nancy Cheruiyot
Investment in The Coconut Industry by Nancy CheruiyotInvestment in The Coconut Industry by Nancy Cheruiyot
Investment in The Coconut Industry by Nancy Cheruiyotictsugar
 
Kenya Coconut Production Presentation by Dr. Lalith Perera
Kenya Coconut Production Presentation by Dr. Lalith PereraKenya Coconut Production Presentation by Dr. Lalith Perera
Kenya Coconut Production Presentation by Dr. Lalith Pereraictsugar
 
TriStar Gold Corporate Presentation - April 2024
TriStar Gold Corporate Presentation - April 2024TriStar Gold Corporate Presentation - April 2024
TriStar Gold Corporate Presentation - April 2024Adnet Communications
 
Chapter 9 PPT 4th edition.pdf internal audit
Chapter 9 PPT 4th edition.pdf internal auditChapter 9 PPT 4th edition.pdf internal audit
Chapter 9 PPT 4th edition.pdf internal auditNhtLNguyn9
 
8447779800, Low rate Call girls in New Ashok Nagar Delhi NCR
8447779800, Low rate Call girls in New Ashok Nagar Delhi NCR8447779800, Low rate Call girls in New Ashok Nagar Delhi NCR
8447779800, Low rate Call girls in New Ashok Nagar Delhi NCRashishs7044
 
APRIL2024_UKRAINE_xml_0000000000000 .pdf
APRIL2024_UKRAINE_xml_0000000000000 .pdfAPRIL2024_UKRAINE_xml_0000000000000 .pdf
APRIL2024_UKRAINE_xml_0000000000000 .pdfRbc Rbcua
 
Unlocking the Future: Explore Web 3.0 Workshop to Start Earning Today!
Unlocking the Future: Explore Web 3.0 Workshop to Start Earning Today!Unlocking the Future: Explore Web 3.0 Workshop to Start Earning Today!
Unlocking the Future: Explore Web 3.0 Workshop to Start Earning Today!Doge Mining Website
 
Entrepreneurship lessons in Philippines
Entrepreneurship lessons in  PhilippinesEntrepreneurship lessons in  Philippines
Entrepreneurship lessons in PhilippinesDavidSamuel525586
 
Organizational Structure Running A Successful Business
Organizational Structure Running A Successful BusinessOrganizational Structure Running A Successful Business
Organizational Structure Running A Successful BusinessSeta Wicaksana
 
Call Us 📲8800102216📞 Call Girls In DLF City Gurgaon
Call Us 📲8800102216📞 Call Girls In DLF City GurgaonCall Us 📲8800102216📞 Call Girls In DLF City Gurgaon
Call Us 📲8800102216📞 Call Girls In DLF City Gurgaoncallgirls2057
 
Independent Call Girls Andheri Nightlaila 9967584737
Independent Call Girls Andheri Nightlaila 9967584737Independent Call Girls Andheri Nightlaila 9967584737
Independent Call Girls Andheri Nightlaila 9967584737Riya Pathan
 
(Best) ENJOY Call Girls in Faridabad Ex | 8377087607
(Best) ENJOY Call Girls in Faridabad Ex | 8377087607(Best) ENJOY Call Girls in Faridabad Ex | 8377087607
(Best) ENJOY Call Girls in Faridabad Ex | 8377087607dollysharma2066
 
Financial-Statement-Analysis-of-Coca-cola-Company.pptx
Financial-Statement-Analysis-of-Coca-cola-Company.pptxFinancial-Statement-Analysis-of-Coca-cola-Company.pptx
Financial-Statement-Analysis-of-Coca-cola-Company.pptxsaniyaimamuddin
 
8447779800, Low rate Call girls in Uttam Nagar Delhi NCR
8447779800, Low rate Call girls in Uttam Nagar Delhi NCR8447779800, Low rate Call girls in Uttam Nagar Delhi NCR
8447779800, Low rate Call girls in Uttam Nagar Delhi NCRashishs7044
 

Último (20)

Innovation Conference 5th March 2024.pdf
Innovation Conference 5th March 2024.pdfInnovation Conference 5th March 2024.pdf
Innovation Conference 5th March 2024.pdf
 
Memorándum de Entendimiento (MoU) entre Codelco y SQM
Memorándum de Entendimiento (MoU) entre Codelco y SQMMemorándum de Entendimiento (MoU) entre Codelco y SQM
Memorándum de Entendimiento (MoU) entre Codelco y SQM
 
NewBase 19 April 2024 Energy News issue - 1717 by Khaled Al Awadi.pdf
NewBase  19 April  2024  Energy News issue - 1717 by Khaled Al Awadi.pdfNewBase  19 April  2024  Energy News issue - 1717 by Khaled Al Awadi.pdf
NewBase 19 April 2024 Energy News issue - 1717 by Khaled Al Awadi.pdf
 
Investment in The Coconut Industry by Nancy Cheruiyot
Investment in The Coconut Industry by Nancy CheruiyotInvestment in The Coconut Industry by Nancy Cheruiyot
Investment in The Coconut Industry by Nancy Cheruiyot
 
Japan IT Week 2024 Brochure by 47Billion (English)
Japan IT Week 2024 Brochure by 47Billion (English)Japan IT Week 2024 Brochure by 47Billion (English)
Japan IT Week 2024 Brochure by 47Billion (English)
 
Kenya Coconut Production Presentation by Dr. Lalith Perera
Kenya Coconut Production Presentation by Dr. Lalith PereraKenya Coconut Production Presentation by Dr. Lalith Perera
Kenya Coconut Production Presentation by Dr. Lalith Perera
 
TriStar Gold Corporate Presentation - April 2024
TriStar Gold Corporate Presentation - April 2024TriStar Gold Corporate Presentation - April 2024
TriStar Gold Corporate Presentation - April 2024
 
Chapter 9 PPT 4th edition.pdf internal audit
Chapter 9 PPT 4th edition.pdf internal auditChapter 9 PPT 4th edition.pdf internal audit
Chapter 9 PPT 4th edition.pdf internal audit
 
8447779800, Low rate Call girls in New Ashok Nagar Delhi NCR
8447779800, Low rate Call girls in New Ashok Nagar Delhi NCR8447779800, Low rate Call girls in New Ashok Nagar Delhi NCR
8447779800, Low rate Call girls in New Ashok Nagar Delhi NCR
 
APRIL2024_UKRAINE_xml_0000000000000 .pdf
APRIL2024_UKRAINE_xml_0000000000000 .pdfAPRIL2024_UKRAINE_xml_0000000000000 .pdf
APRIL2024_UKRAINE_xml_0000000000000 .pdf
 
Unlocking the Future: Explore Web 3.0 Workshop to Start Earning Today!
Unlocking the Future: Explore Web 3.0 Workshop to Start Earning Today!Unlocking the Future: Explore Web 3.0 Workshop to Start Earning Today!
Unlocking the Future: Explore Web 3.0 Workshop to Start Earning Today!
 
Entrepreneurship lessons in Philippines
Entrepreneurship lessons in  PhilippinesEntrepreneurship lessons in  Philippines
Entrepreneurship lessons in Philippines
 
Organizational Structure Running A Successful Business
Organizational Structure Running A Successful BusinessOrganizational Structure Running A Successful Business
Organizational Structure Running A Successful Business
 
No-1 Call Girls In Goa 93193 VIP 73153 Escort service In North Goa Panaji, Ca...
No-1 Call Girls In Goa 93193 VIP 73153 Escort service In North Goa Panaji, Ca...No-1 Call Girls In Goa 93193 VIP 73153 Escort service In North Goa Panaji, Ca...
No-1 Call Girls In Goa 93193 VIP 73153 Escort service In North Goa Panaji, Ca...
 
Call Us 📲8800102216📞 Call Girls In DLF City Gurgaon
Call Us 📲8800102216📞 Call Girls In DLF City GurgaonCall Us 📲8800102216📞 Call Girls In DLF City Gurgaon
Call Us 📲8800102216📞 Call Girls In DLF City Gurgaon
 
Independent Call Girls Andheri Nightlaila 9967584737
Independent Call Girls Andheri Nightlaila 9967584737Independent Call Girls Andheri Nightlaila 9967584737
Independent Call Girls Andheri Nightlaila 9967584737
 
(Best) ENJOY Call Girls in Faridabad Ex | 8377087607
(Best) ENJOY Call Girls in Faridabad Ex | 8377087607(Best) ENJOY Call Girls in Faridabad Ex | 8377087607
(Best) ENJOY Call Girls in Faridabad Ex | 8377087607
 
Financial-Statement-Analysis-of-Coca-cola-Company.pptx
Financial-Statement-Analysis-of-Coca-cola-Company.pptxFinancial-Statement-Analysis-of-Coca-cola-Company.pptx
Financial-Statement-Analysis-of-Coca-cola-Company.pptx
 
8447779800, Low rate Call girls in Uttam Nagar Delhi NCR
8447779800, Low rate Call girls in Uttam Nagar Delhi NCR8447779800, Low rate Call girls in Uttam Nagar Delhi NCR
8447779800, Low rate Call girls in Uttam Nagar Delhi NCR
 
Enjoy ➥8448380779▻ Call Girls In Sector 18 Noida Escorts Delhi NCR
Enjoy ➥8448380779▻ Call Girls In Sector 18 Noida Escorts Delhi NCREnjoy ➥8448380779▻ Call Girls In Sector 18 Noida Escorts Delhi NCR
Enjoy ➥8448380779▻ Call Girls In Sector 18 Noida Escorts Delhi NCR
 

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');