Copyrights © 2012 Jatin Kotadiya. All Rights Reserved . Powered by Blogger.

Tuesday, October 23, 2012

PHP


Introduction Smarty :
·         Smarty is a template engine for PHP. More specifically, it facilitates a manageable way to separate application logic and content from its presentation.
·         This is best described in a situation where the application programmer and the template designer play different roles, or in most cases are not the same person.


Variables assigned from PHP :
- Variables that are assigned from PHP are referenced by preceding them with a dollar sign $ (like php).

- Variables assigned from within a template with the {assign}function are also displayed this way.

Example :
.Php File                :
<?php
 
$smarty = new Smarty();
 
$smarty->assign('firstname', 'Harshad');
$smarty->assign('lastname', 'Fefar');
$smarty->assign('meetingPlace', 'Rajkot');
 
$smarty->display('index.tpl');
 
?>

.Tpl File :
Hello {$firstname} {$lastname}, glad to see you can make it.
<br />
 
{* this will not work as $variables are case sensitive *}
 
This weeks meeting is in {$meetingplace}.
 
{* this will work *}
This weeks meeting is in {$meetingPlace}.



Out Put :
Hello Harshad Fefar, glad to see you can make it.
<br />
This weeks meeting is in .
This weeks meeting is in Rajkot.


Variables loaded from config files :

Variables that are loaded from the config files are referenced by enclosing them within #hash marks#, or with the smarty variable $smarty.config.

Example :

Foo.conf
pageTitle = "This is mine"
bodyBgColor = '#eeeeee'
tableBorderSize = 3
tableBgColor = "#bbbbbb"
rowBgColor = "#cccccc"

A template demonstrating the #hash# method :




{config_load file='foo.conf'}
<html>
<title>{#pageTitle#}</title>
<body bgcolor="{#bodyBgColor#}">
<table border="{#tableBorderSize#}" bgcolor="{#tableBgColor#}">
<tr bgcolor="{#rowBgColor#}">
    <td>First</td>
    <td>Last</td>
    <td>Address</td>
</tr>
</table>
</body>
</html>
 
    

A template demonstrating the $smarty.config method:

{config_load file='foo.conf'}
<html>
<title>{$smarty.config.pageTitle}</title>
<body bgcolor="{$smarty.config.bodyBgColor}">
<table border="{$smarty.config.tableBorderSize}" bgcolor="{$smarty.config.tableBgColor}">
<tr bgcolor="{$smarty.config.rowBgColor}">
    <td>First</td>
    <td>Last</td>
    <td>Address</td>
</tr>
</table>
</body>
</html>
Output :




<html>
<title>This is mine</title>
<body bgcolor="#eeeeee">
<table border="3" bgcolor="#bbbbbb">
<tr bgcolor="#cccccc">
                    <td>First</td>
                    <td>Last</td>
                    <td>Address</td>
</tr>
</table>
</body>
</html>







Variable Modifiers

( 1 ) Capitalize :

This is used to capitalize the first letter of all words in a variable. This is similar to the PHP ucwords() function.

Example :

.PHP File
<?php
     $smarty->assign('name', 'my name is harshad fefar');
?>

Where the template is:
{$name}<br />
{$name|capitalize}

Output :
my name is harshad fefar
My Name Is Harshad Fefar

( 2 ) Lower :

            This is used to lowercase a variable. This is equivalent to the PHP strtolower() function.

Example :

.PHP File
<?php
    $smarty->assign('college', ‘HARIVANDANA COLLEGE , RAJKOT');
?

Where the template is:
{$college}
{$college|lower}

Output :
HARIVANDANA COLLEGE , RAJKOT
Harivandana college , rajkot


( 3 ) upper :

This is used to uppercase a variable. This is equivalent to the PHP strtoupper() function.

Example :

.PHP File
<?php
        $smarty->assign('college', ‘harivandana college’);
?>

Where template is:
{$college}
{$college|upper}

Output :
Harivandana college
HARIVANDANA COLLEGE

(4) truncate :
           
            - This truncates a variable to a character length, the default is 80.

- As an optional second parameter, you can specify a string of text to display at the end if the variable was truncated. The characters in the string are included with the original truncation length. By default, truncate will attempt to cut off at a word boundary.

Example :

.PHP File
<?php
    $smarty->assign('college', 'harivandana parivar');
?>

Where template is :
{$college}
{$college|truncate:15: ""}
{$college|truncate:15:"---"}
{$college|truncate:15:"":true}

Output :
harivandana parivar
harivandana 
harivandana ---
harivandana par



( 5 ) count_characters :

            This is used to count the number of characters in a variable.

Example :

.PHP File
<?php
      $smarty->assign('name', 'Harshad Fefar');
?>

Where template is :
{$name}
{$name|count_characters}
{$name|count_characters:true}

Output :
Harshad Fefar
12
13

( 6 ) count_words
           
            This is used to count the number of words in a variable.

Example :

.PHP File
<?php
      $smarty->assign('name', 'Harshad Fefar');
?>

Where template is :
{$name}
{$name|count_words}   

Output :
Harshad Fefar
2

( 7 ) nl2br :
           
            All "\n" line breaks will be converted to html <br /> tags in the given variable. This is equivalent to the PHP's nl2br() function.



Example :

<?php
                    $smarty->assign('ex',"Hello world\n how are you");
 
?>

Where template is :
{$ex|nl2br}

Output :
Hello world
How are you

( 8 ) replace :

            A simple search and replace on a variable. This is equivalent to the PHP's str_replace() function.

Example :

.PHP File
<?php
    $smarty->assign('name', "This is a cow.");
?>

Where template is :
{$name}
{$name|replace:'cow':'dog'}

Output :
This is a cow.
This is a dog.


Built in function

( 1 ) config_load :
                  
                         {config_load} is used for loading config #variables# from a configuration file into the template.

Example :

.conf file
pagetitle = “Google.com”
bgcolor=”red”

And the template file
{config_load file="example.conf"}
 
<html>
<title>{#pagetitle#}</title>
<body bgcolor="{#bgcolor#}">
</body>
</html>

( 2 ) foreach || foreachelse :

                   {foreach} is used to loop over an associative array as well a numerically-indexed array, unlike {section} which is for looping over numerically-indexed arrays only. The syntax for {foreach} is much easier than {section}, but as a tradeoff it can only be used for a single array. Every {foreach} tag must be paired with a closing {/foreach} tag.

Example : {foreach}

.PHP File
<?php
        $arr = array(1000, 1001, 1002);
        $smarty->assign('myArray', $arr);
?>

Where template file :
<ul>
                    {foreach from=$myArray item=foo}
                                           <li>{$foo}</li>
                    {/foreach}
</ul>

Output :
<ul>
    <li>1000</li>
    <li>1001</li>
    <li>1002</li>
</ul>

Example : {foreachelse}

.PHP File
<?php
        $arr = array();
        $smarty->assign('myArray', $arr);
?>

Where template file :
<ul>
                    {foreach from=$myArray item=foo}
                                           <li>{$foo}</li>
                    {foreachelse}
                                         No Record Found.
                    {/foreachelse}
</ul>

Output :
<ul>
    <li>1000</li>
    <li>1001</li>
    <li>1002</li>
</ul>

( 3 ) include :
                  
                   {include} tags are used for including other templates in the current template. Any variables available in the current template are also available within the included template.

Example :

.tpl File
<html>
                    <head>
                                         <title>{$title}</title>
                    </head>
                    <body>
                                         {include file='page_header.tpl'}
                    </body>
</html>

Page_header.tpl:
Hello world


( 4 ) if | elseif | else :
{if} statements in Smarty have much the same flexibility as PHP if statements, with a few added features for the template engine. Every {if} must be paired with a matching {/if}. {else} and {elseif} are also permitted. All PHP conditionals and functions are recognized, such as ||, or, &&, and, is_array(), etc.

Qualifier
Alternates
Syntax Example
Meaning
PHP Equivalent
==
eq
$a eq $b
equals
==
!=
ne, neq
$a neq $b
not equals
!=
> 
gt
$a gt $b
greater than
> 
< 
lt
$a lt $b
less than
< 
>=
gte, ge
$a ge $b
greater than or equal
>=
<=
lte, le
$a le $b
less than or equal
<=
===

$a === 0
check for identity
===
!
not
not $a
negation (unary)
!
%
mod
$a mod $b
modulous
%
is [not] div by

$a is not div by 4
divisible by
$a % $b == 0
is [not] even

$a is not even
[not] an even number (unary)
$a % 2 == 0
is [not] even by

$a is not even by $b
grouping level [not] even
($a / $b) % 2 == 0
is [not] odd

$a is not odd
[not] an odd number (unary)
$a % 2 != 0
is [not] odd by

$a is not odd by $b
[not] an odd grouping
($a / $b) % 2 != 0
Example :
{if $name eq 'Fred'}
    Welcome Sir.
{elseif $name eq 'Wilma'}
    Welcome Ma'am.
{else}
    Welcome, whatever you are.
{/if}




Custom Functions

( 1 ) assign :
           
            {assign} is used for assigning template variables during the execution of a template.

Example :

.tpl File :
{assign var='name' value='Harshad Fefar'}
 
The value of $name is {$name}.

Output :
The value of $name is Harshad Fefar.

( 2 ) counter :

            {counter} is used to print out a count. {counter} will remember the count on each iteration. You can adjust the number, the interval and the direction of the count, as well as determine whether or not to print the value.

Example :

.tpl File
{* initialize the count *}
{counter start=0 skip=2}<br />
{counter}<br />
{counter}<br />
{counter}<br />

Output :
0<br />
2<br />
4<br />
6<br /> 

( 3 ) Cycle :
           
            {cycle} is used to alternate a set of values. This makes it easy to for example, alternate between two or more colors in a table, or cycle through an array of values.



Example :

.tpl File :
{section name=rows loop=$data}
<tr class="{cycle values="odd,even"}">
   <td>{$data[rows]}</td>
</tr>
{/section}

Output :
<tr class="odd">
   <td>1</td>
</tr>
<tr class="even">
   <td>2</td>
</tr>
<tr class="odd">
   <td>3</td>
</tr>

( 4 ) eval :

{eval} is used to evaluate a variable as a template. This can be used for things like embedding template tags/variables into variables or tags/variables into config file variables.

Example :

.conf File
emphstart = <strong>
emphend = </strong>
title = Welcome to {$company}'s home page!
ErrorCity = You must supply a {#emphstart#}city{#emphend#}.
ErrorState = You must supply a {#emphstart#}state{#emphend#}.

.tpl File
{eval var=#title#}
{eval var=#ErrorCity#}
{eval var=#ErrorState# }



( 5 ) Fetch :

{fetch} is used to retrieve files from the local file system, http, or ftp and display the contents.

Example :

{* embed some weather text in your template from another web site *}
{fetch file='http://www.myweather.com/68502/'}

( 6 ) html_checkboxes :
           
            {html_checkboxes} is a custom function  that creates an html checkbox group with provided data. It takes care of which item(s) are selected by default as well.

Example :

.PHP File :
<?php
 
$smarty->assign('cust_ids', array(1000,1001,1002,1003));
$smarty->assign('cust_names', array(
                                'Joe Schmoe',
                                'Jack Smith',
                                'Jane Johnson',
                                'Charlie Brown')
                              );
$smarty->assign('customer_id', 1001);
 
?>

.tpl File
{html_checkboxes name='id' values=$cust_ids output=$cust_names
   selected=$customer_id  separator='<br />'}

Output :
<label><input type="checkbox" name="id[]" value="1000" />Joe Schmoe</label><br />
<label><input type="checkbox" name="id[]" value="1001" checked="checked" />Jack Smith</label>
<br />
<label><input type="checkbox" name="id[]" value="1002" />Jane Johnson</label><br />
<label><input type="checkbox" name="id[]" value="1003" />Charlie Brown</label><br />



( 7 ) html_image :

            {html_image} is a custom function that generates an HTML <img> tag. The height and width are automatically calculated from the image file if they are not supplied.

Example :

.tpl File
{html_image file='pumpkin.jpg'}
{html_image file='/path/from/docroot/pumpkin.jpg'}
{html_image file='../path/relative/to/currdir/pumpkin.jpg'}

Output :
<img src="pumpkin.jpg" alt="" width="44" height="68" />
<img src="/path/from/docroot/pumpkin.jpg" alt="" width="44" height="68" />
<img src="../path/relative/to/currdir/pumpkin.jpg" alt="" width="44" height="68" />

( 8 ) html_options :

            {html_options} is a custom function that creates the html <select><option> group with the assigned data. It takes care of which item(s) are selected by default as well.           

Example :

.PHP File
<?php
$smarty->assign('myOptions', array(
                                1800 => 'Joe Schmoe',
                                9904 => 'Jack Smith',
                                2003 => 'Charlie Brown')
                                );
$smarty->assign('mySelect', 9904);
?>

.tpl File :
{html_options name=foo options=$myOptions selected=$mySelect}

Output :
<select name="foo">
<option label="Joe Schmoe" value="1800">Joe Schmoe</option>
<option label="Jack Smith" value="9904" selected="selected">Jack Smith</option>
<option label="Charlie Brown" value="2003">Charlie Brown</option>
</select>



( 9 ) html_radios :
           
            {html_radios} is a custom function that creates a HTML radio button group. It also takes care of which item is selected by default as well.

Example :

.PHP File
<?php
 
$smarty->assign('cust_ids', array(1000,1001,1002,1003));
$smarty->assign('cust_names', array(
                              'Joe Schmoe',
                              'Jack Smith',
                              'Jane Johnson',
                              'Charlie Brown')
                              );
$smarty->assign('customer_id', 1001);
 
?>

.tpl File
{html_radios name='id' values=$cust_ids output=$cust_names
       selected=$customer_id separator='<br />'}   

Output :
<label for="id_1000">
<input type="radio" name="id" value="1000" id="id_1000" />Joe Schmoe</label><br />
<label for="id_1001"><input type="radio" name="id" value="1001" id="id_1001" checked="checked" />Jack Smith</label><br />
<label for="id_1002"><input type="radio" name="id" value="1002" id="id_1002" />Jane Johnson</label><br />
<label for="id_1003"><input type="radio" name="id" value="1003" id="id_1003" />Charlie Brown</label><br />


(10)  html_select_date :
           
            {html_select_date} is a custom function that creates date dropdowns. It can display any or all of year, month, and day. All parameters that are not in the list below are printed as name/value-pairs inside the <select> tags of day, month and year.

Example :

.tpl File
{html_select_date}  


Output :
<select name="Date_Month">
<option value="1">January</option>
<option value="2">February</option>
<option value="3">March</option>
  ..... snipped .....
<option value="10">October</option>
<option value="11">November</option>
<option value="12" selected="selected">December</option>
</select>
<select name="Date_Day">
<option value="1">01</option>
<option value="2">02</option>
<option value="3">03</option>
  ..... snipped .....
<option value="11">11</option>
<option value="12">12</option>
<option value="13" selected="selected">13</option>
<option value="14">14</option>
<option value="15">15</option>
  ..... snipped .....
<option value="29">29</option>
<option value="30">30</option>
<option value="31">31</option>
</select>
<select name="Date_Year">
<option value="2006" selected="selected">2006</option>
</select>

( 11 ) html_select_time :
           
            {html_select_time} is a custom function that creates time dropdowns for you. It can display any or all of hour, minute, second and meridian.

Example :

.tpl File :
{html_select_time use_24_hours=true}

Output :
<select name="Time_Hour">
<option value="00">00</option>
<option value="01">01</option>
... snipped ....
<option value="08">08</option>
<option value="09" selected>09</option>
<option value="10">10</option>
... snipped ....
<option value="22">22</option>
<option value="23">23</option>
</select>
<select name="Time_Minute">
<option value="00">00</option>
<option value="01">01</option>
... snipped ....
<option value="19">19</option>
<option value="20" selected>20</option>
<option value="21">21</option>
... snipped ....
<option value="58">58</option>
<option value="59">59</option>
</select>
<select name="Time_Second">
<option value="00">00</option>
<option value="01">01</option>
... snipped ....
<option value="22">22</option>
<option value="23" selected>23</option>
<option value="24">24</option>
... snipped ....
<option value="58">58</option>
<option value="59">59</option>
</select>
<select name="Time_Meridian">
<option value="am" selected>AM</option>
<option value="pm">PM</option>
</select>


0 comments:

Post a Comment