PHP Basics Review (i) Smarty templates

Source: Internet
Author: User
Tags php basics

One. Basic Configuration
First step: Download Smarty: official website www.smarty.net
Step two: Load class files and change configuration

1.//Load class file

Require_once '. /libs/smarty.class.php ';
Instantiating an Object
$smarty =new smarty ();
Change configuration If you don't change it, you don't have to write
$smarty->settemplatedir ('./templates ');//Set Template directory
$smarty->setcompiledir ('./templates_c ');//Set compilation directory
$smarty->setcachedir ('./cache ');//Set Cache directory
$smarty->setconfigdir ('./configs ');//Set the directory where the configuration files are located
$smarty->addpluginsdir ('./plugins ');//Add plugin Directory
$smarty->left_delimiter= ' {';
$smarty->right_delimiter= '} ';
Setting up the cache
$smarty->debugging = true; Open Debug Window
$smarty->caching = true;
$smarty->cache_lifetime = 120;
Step three: License variables and display
$smarty->assign (' Chen ', ' 123 ');
Display templates
$smarty->display (' 1.html ');

Two. Common types of output
$smarty->assign (' int ', php_int_max);
$smarty->assign (' float ', 12.3);
$smarty->assign (' bool ', true);
$smarty->assign (' string ', ' This is a test ');
$smarty->assign (' arr ', Array (' A ', ' B ', ' C ', ' username ' = ' king ', ' age ' =>12));
$smarty->assign (' arr1 ', Array (' A ' =>array (), ' B ' =>array (11,22,33)));
$smarty->assign (' obj ', New Test ());
$smarty->assign (' Resource ', fopen (' index.php ', ' r '));
$smarty->assign (' null ', NULL);
Class test{
public $username;
Public $email;
Public $sex;
Public Function __construct () {
$this->username= ' King ';
$this->email= ' [email protected] ';
$this->sex= ' man ';
}
Public Function Sayhi () {
Echo ' Say Hi to everybody<br/> ';
}
Public Function test () {
Return ' This is a test ';
}
}
Third, template comments
{* Template comments, comments will not appear in the final output of the template file *}
{* This is not the same as HTML comments *}
Iv. Defining variables in templates
Declaring variables in a template by assign
{Assign Var=num1 value=1}
num1:{$num 1} <br/>
declaring variables
{$test = "Hello"}
{$test} <br/>
Tag nesting
{$test 1= "{$test} chen"}
{$test 1} <br/>
Declaring an array
{Assign VAR=ARR3 value=[1,2,3]}
{$arr 3.0} <br/>
{$arr 3[1]} <br/>
{Assign VAR=ARR4 value=[' username ' = ' Queen ', ' age ' =>12]}
{$arr 4.username} <br/>
{$arr 4[' age '} <br/>
{$arr 5=[' a ', ' B ', ' C ', [' Test ' = ' test ', ' test1 ' = ' test1 ', ' Eee ']}
{$arr 5.0} <br/>
{$arr 5[3][' test '} <br/>
{$arr 5[3][0]} <br/>
Variable variable
{$world = ' world '}
{$hello _world= "This was Hello World"}
{$hello _{$world} <br/>
Four, pre-reserved variables

Session_Start ();
$_session[' username ']= ' admin ';
$_session[' id ']=1;
Define (' Test ', ' This is a TEST ');

In the template
{$smarty. Session.username}
{$smarty. Session.id}
Pre-reserved variables that you can use
1> page Request Variable
$smarty. Get.page equivalent to $_get[' page ' in PHP
$smarty. Post.page equivalent to $_post[' page ' in PHP
$smarty. Cookies.username equivalent to PHP $_cookie[' username ']
$smarty. Session.username equivalent to PHP $_session[' username ']
$smarty. Server.server_name equivalent to PHP $_server[' server_name ']
$smarty. Env.path equivalent to $_env[' PATH ' in PHP
$smarty. Request.username equivalent to PHP $_request[' username ']
Get the current timestamp
{$smarty. Now}
{$smarty. Now|date_format: '%y-%m-%d%h:%m:%s '}
{Time ()}
{Date ("y-m-d h:i:s", Time ())}
Get the value of a constant in a PHP script
PHP version: {$smarty. const.php_version} <br/>
Php_os: {$smarty. const.php_os} <br/>
{$smarty. Const.test}
Get the values in the configuration file
{config_load "reset.conf"}
title:{$smarty. config.title} <br/>
title:{#title #} <br/>
Returns the currently processed template name (without directories)
Current template name: {$smarty. template} <br/>
Returns the current template directory name
Current Template catalog name: {$smarty. current_dir} <br/>
Returns the version number of the Smarty
Smarty version:{$smarty. Version} <br/>
Returns the current left and right delimiters
Left delimiter: {$smarty. Ldelim} <br/>
Right delimiter: {$smarty. Rdelim} <br/>
Other commonly used:
{$smarty. Capture}: Capture the built-in capture template output
{$smarty. Section}: A property used to point to a section loop
{$smarty. Block.child}: Returns the sub-template text block
{$smarty. Block.parent}: Returns the parent template text block

Five, variable regulator
Capitalize: Capitalize the first letter of the word in the variable, ucwords*
Capitalize the first letter of the word: {$test |capitalize}
{$test |ucwords}
{*count_characters: Calculates the number of characters in the variable value,
The parameter value Boolean determines whether to calculate the number of spaces, which is not calculated by default *}
Number of characters: {$test |count_characters}
Number of characters with spaces: {$test |count_characters:true}
Cat: Connect the parameter value in cat to the given variable, which is empty by default
Connection characters: {$test |cat: '! ': ' <br/> ': ' Hello world! ': ' Maizixueyuan '}
Count_paragraphs: Calculating the number of paragraphs in a variable
Number of paragraphs: {$content |count_paragraphs}
Count_sentences: Calculates a sentence in a variable, separated by a dot, question mark, or exclamation mark (.?!).
Sentence in paragraph: {$content |count_sentences}
Count_words: Calculating the number of words in a variable
Number of words: {$content |count_words}
Date_format: Date formatting
{$smarty. Now|date_format: "%y-%m-%d"} <br/>
Assigning an initial value
Assign an initial value to the variable: {$kickName |default: ' King '} <br/>
{*escape html transcoding, url transcoding, etc., default is HTML transcoding *}
No transcoding by default
{$string} <br/>
Convert HTML entities or write escape: ' HTML '
{$string |escape} <br/>
{$string |escape: ' html '} <br/>
Lower|upper convert to lowercase or uppercase
{$string 1|lower} <br/>
{$string 1|upper} <br/>
Indent produces indentation, the first parameter specifies how many characters are indented, and the default is four characters;
The second argument, specifying what character to indent with instead of
{$string 1|indent:4} <br/>
{$string 1|indent:4: ' * '} <br/>
NL2BR converts a newline character in a string to a <br/> nl2br () in PHP
{$string 2|nl2br} <br/>
Replace: string substitution, the first parameter is the content of the search;
The second parameter is the content to be replaced after the search;
Equivalent to the Str_replace () function in PHP *}
{$string 2|replace: ' Maizi ': ' Wheat '} <br/>
Spacify: Inserts a space or other character between each character in a string, by default a space
{$string 2|spacify} <br/>
{$string 2|spacify: ' * '} <br/>
Strip: Replace all repeating spaces, wrap and tab to single or specified string;
You can specify a string to replace
*}
{$string 2|strip} <br/>
{$string 2|strip: '? '} <br/>
{*strip_tags: Remove all HTML tags *}
{$string 3} <br/>
{$string 3|strip_tags} <br/>
{*string_format: Formatted string *}
{$number = 3.1415926}
{$number} <br/>
{$number |string_format: "%.2f"} <br/>
{$number |string_format: '%d '} <br/>
For the same variable, you can use multiple modifiers. They are then combined from left to right in a set order. You must use the "|" Characters as delimiters between them.
Convert to entity | lowercase | indent with *
{$string |escape|lower|indent: ' 4 ': ' * '} <br/>
You can also use PHP's system functions
{$string 4= ' maiziedu '}
{$string 4|substr:2:2} <br/>
{$string 4|strtoupper} <br/>
The default variable regulator function in the system is a plugin that comes with Smarty
It's all in the plugins directory.
{$filename = ' 1.txt.jpeg '}
{$filename |ext} <br/>
{$string 4|font: ' 20px ': ' Green ': ' Microsoft yahei ': ' Normal '}
{$string 4|font: ' 30px ': ' Purple ': ' Chinese Choi Wan ': ' Bold '} <br/>
{$string 4|strshuffle} <br/>

Six, built-in functions in Smarty templates
Assign declaring variables
{assign var= ' username ' value= ' king '}
User name: {$username} <br/>
The abbreviated
{assign username test}
User name equivalent to the Assign function property: {$username} <br/>
equivalent to assign abbreviation, write variable name = value
{$username = ' Queen '}
Username: {$username} <br/>
{$array =[' a ', ' B ', ' C ', +]}
{$array. 0} <br/>
Dynamically appending elements via append
{append var= ' array ' value= ' d '}
{append var= ' array ' value= ' king ' index= ' username '}
{Print_r ( $array)}
{$username = ' Maizi '}
1, if
{if $username = = ' Maizi '
Welcome <br/>
{/if}
3, If...else
{if $username eq ' maizi1 '}
Hello Maizi1 <br/>
{Else}
Hello everybody <br/>
{/if}
3, if ... elseif ...
{$day =3}
{if $day ==1}
Monday <br/>
{elseif $day ==2}
Tuesday <br/>
{else}
Illegal date
{/if}
4, is (not) div by can be divisible
{$num 1=8}
{if $num 1 is div by 4}
divisible <br/>
{Else}
cannot be divisible <br/>
{/I F}

5, Is[not] Even is an even number
{$num 1=3}
{If $num 1 is not even}
Not even <br/>
{Else}
is even <br/>
{/if}


6. For loop
A simple loop with a step size of 1
{for $var =1 to 10}
{$var} <br/>
{/for}

Set Step size
{for $var =1 to step 2}
{$var} <br/>
{/for}

Set the maximum number of cycles with Max
{for $var =1 to step 2 max=10}
{$var} <br/>
{/for}

Forelse can be used when the loop condition is not established
{for $var =5 to 1}
{$var} <br/>
{Forelse}
Code <BR executed when the loop condition is not established/>
{/for}


Using the While loop
{$var = 10}
{While $var >=0}
{$var--} <br/>
{/while}


Traversal arrays can be traversed by foreach and section
Traversal through foreach *
{$arr =[' a ', ' B ', ' C ', ' d ']}
{if Is_array ($arr)}
{foreach $arr as $k = + $v}
Key name ={$k}---Key value ={$v}
{/foreach}
{foreach $arr as $v}
Key value ={$v} <br/>
{/foreach}
{* If you do not specify an array subscript can be obtained by @key *}
{foreach $arr as $v}
Key name ={[email protected]}--key value ={$v} <br/>
{/foreach}
{/if}

Foreachelse can be used when the array has no value
{foreach $arr 1 as $val}
{$val}
{Foreachelse}
No results
{/foreach}

foreach Supports nesting
{foreach $users as $user}
{foreach $user as $val}
{$val} <br/>
{/foreach}
{/foreach}
<table border= ' 1 ' width= ' 80% ' cellpadding= ' 0 ' cellspacing= ' 0 ' >
<tr>
<td> numbering </td>
<td> User name </td>
<td> Email </td>
<td> Address </td>
</tr>
{foreach $users as $user}
<tr>
<td>{$user .id}</td>
<td>{$user .username}</td>
<td>{$user .email}</td>
<td>{$user .addr}</td>
</tr>
{Foreachelse}
<tr>
<TD colspan= ' 4 ' > No users </td>
</tr>
{/foreach}
</table>

There are some common properties in foreach
<table border= ' 1 ' width= ' 80% ' cellpadding= ' 0 ' cellspacing= ' 0 ' >
<tr>
<td> numbering </td>
<td> User name </td>
<td> Email </td>
<td> Address </td>
</tr>
{foreach $users as $user}
{if [email protected]}
<tr bgcolor= ' Red ' >
{ElseIf [email protected]}
<tr bgcolor= ' green ' >
{ElseIf [email protected] is even}
<tr bgcolor= ' Blue ' >
{Else}
<tr>
{/if}
<td>id={$user. Id}--index={[email protected]}--iteration={[email protected]}</td>
<td>{$user .username}</td>
<td>{$user .email}</td>
<td>{$user .addr}</td>
</tr>
{/foreach}
{if [email protected]}
&LT;TR&GT;&LT;TD colspan= ' 4 ' > total {[email protected]} users </td></tr>
{Else}
&LT;TR&GT;&LT;TD colspan= ' 4 ' > No user, please add </td></tr>
{/if}
</table>
Terminating a loop by break
{$arr =[' a ', ' B ', ' C ', ' d ', ' E ']}
{foreach $arr as $val}
{if $val = = ' C '}
{Break}
{/if}
{$val}
{/foreach}

Jump to the next cycle by continue
{$arr =[' a ', ' B ', ' C ', ' d ', ' E ']}
{foreach $arr as $val}
{if $val = = ' C '}
{Continue}
{/if}
{$val}
{/foreach}

VII: Inheritance
$smarty->display (' extends:parent.html|child.html ');

PHP Basics Review (i) Smarty templates

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.