Home > Backend Development > PHP Tutorial > smarty example tutorial_PHP tutorial

smarty example tutorial_PHP tutorial

WBOY
Release: 2016-07-21 16:00:31
Original
897 people have browsed it

smarty example tutorial (1)
1. What is smarty?
smarty is a template PHP template engine written in PHP. It provides a simple separation of logic and external content. To put it bluntly, the purpose is to use PHP programmers and artists to be separated. The programmers used to change the logical content of the program will not affect the artist's page design, and the artist's re-modification of the page will not affect the program logic of the program. This is This is especially important in multi-person cooperation projects
.

2. Advantages of smarty:
1. Speed: Programs written using smarty can achieve maximum speed improvements, which is compared to other template engine technologies.

2. Compiled type: A program written in smarty must be compiled into a non-template technology PHP file at runtime. This file uses a mixture of PHP and HTML. The next time the template is accessed
Convert WEB requests directly into this file without recompiling the template (when the source program has not been changed)

3. Caching technology: a caching technology selected by smarty, which can store users The final HTML file seen is cached into a static HTML page. When the cache attribute of smarty is set to
true, the user's WEB request will be directly converted to this static HTML file within the cachetime period set by smarty. Come on, this is equivalent to calling a static HTML file.

4. Plug-in technology: smarty can customize plug-ins. Plug-ins are actually some custom functions.

5. If/elseif/else/endif can be used in templates. Using judgment statements in template files can very conveniently reformat the template.


3. Places where smarty is not suitable:

1. Content that needs to be updated in real time. For example, like stock display, which needs to update data frequently, using smarty for this type of program will slow down template processing.

2. Small projects. For small projects where the artist and programmer are both simple because the project is simple, using smarty will lose the advantage of rapid PHP development.

4. Install smarty class:

Environment for installing smarty: PHP version 4.06 or above.

The installation method of smarty is very simple. Download smarty.t from http://samrty.php.net... Copy all the files in LIB
into the comm directory to complete the basic installation.

Please see the manual for other advanced installation and usage methods.

5. The use of smarty in templates:

This section will talk about the use of smarty through several examples. Smarty templates are usually identified by .tpl. For the convenience of art, some people write the extension directly as .html, which is also OK
. This article adopts smarty standard writing method: expressed as .tpl as a smarty template.

PHP code:----------------------------------------- ---------------------------------------

Example 1:

Let’s look at a simple example first.
=============================================== ======
index.tpl
=================================== ==================

{* Display is the text included with * in the smarty variable identifier as the comment content *}
{include file ="header.tpl"}{*Page header*}
Hello everyone, my name is {$name}, and you are welcome to read my smarty learning materials.
{include file="foot.tpl"}{*End of page*}

The above example is a tpl template, where:
1. {**} is the comment on the template page , it does not produce any output when smarty parses the template, and is only used by the template designer to annotate the template.
2. {include file="xxx.tpl"}Use this sentence to include a template file into the current page. In the example, head.tpl and foot.tpl that are commonly used in the website are included. You can
Think about it this way, use this sentence to copy all the contents in xxx.tpl to the current statement. Of course, you don’t need to use this sentence. It’s also perfectly fine to copy the content in XXX.tpl to the current sentence
.

3.{$name}: Template variable, the core component in smarty, is contained in the left boundary character {and right boundary character} defined by smarty and is given in the form of a PHP variable. In the smarty program, Use
$smarty->assign("name", "Li Xiaojun"); replace $name in the template with the three words "Li Xiaojun".

The entire example source program is as follows:
==============================
header.tpl
=============================


< ;title>Big brother smarty tutorial





============== =================
foot.tpl
======================== =======


CopyRight(C) by Senior Brother August 2004






================================== ===================
index.tpl
====================== ===============================

{* Display is included with * in the smarty variable identifier The text is the annotation content *}
{include file="header.tpl"}{*Page header*}
Hello everyone, my name is {$name}, and you are welcome to read my smarty learning materials.
{include file="foot.tpl"}{*End of page*}

========================= =======================
index.php
================== ==============================

include_once("./comm/ Smarty.class.php"); //Contains smarty class files

$smarty = new Smarty(); //Create smarty instance objects $smarty
$smarty->templates("./templates "); //Set the template directory
$smarty->templates_c("./templates_c"); //Set the compilation directory

//------------ ----------------------------------------
//Left and right boundary characters, default is {}, but in actual application it is easy to conflict with Javascript
//, so it is recommended to set it to <{}> or others.
//------------------------------------------------ -------
$smarty->left_delimiter = "{";
$smarty->right_delimiter = "}";

$smarty->assign("name ", "Li Xiaojun"); //Replace template variables

//Compile and display the index.tpl template located under ./templates
$smarty->display("index.tpl") ;
?>

When this program is finally executed, it will be displayed as:
========================== =======
Execute index.php
==================================


My name is Li Xiaojun, and everyone is welcome to read my smarty learning materials.
                                                                       /html>

smarty instance tutorial (2)
This example is an example of comprehensive use of smarty template parameters. These parameters are used to control the output of the template. I only selected a few of them. You can choose the other parameters. Go check it out for reference.



====================================== ==========
exmple2.tpl
=============================== =================

Big brother smarty example 2

                                                                                  1. The first letter of the first sentence should be capitalized: {$str1|capitalize}
"}

3. The third sentence outputs the current date: {$str3|date_format:"%Y year %m month %d day"}
4. The fourth sentence is not processed in the php program , it displays the default value: {$str4|default: "No value!"}
5. The fifth sentence should be indented by 8 blank characters and use "*" to replace these 8 blank characters:
;
6. In the sixth sentence, change all TEACHerLI@163.com to lowercase: {$str6|lower}

7. In the seventh sentence, replace teacherli in the variable with: Li Xiaojun: {$ str7|replace:"teacherli":"李晓君"}

8. The eighth sentence is a combination of variable modifiers: {$str8|capitalize|cat:"Here is the newly added time:"|date_format :"%Y year %m month %d day"|lower}
                                                                                                 ==================================
example2.php
======= ========================================

include_once("./Smarty.class.php"); //Include smarty class files

$smarty = new Smarty(); //Create smarty instance object $smarty
$smarty- >templates("./templates"); //Set the template directory
$smarty->templates_c("./templates_c"); //Set the compilation directory

//---- ---------------------------------------------
//The left and right boundary characters are {} by default, but in actual application it is easy to conflict with Javascript
//, so it is recommended to set it to <{}> or others.
//------------------------------------------------ -------
$smarty->left_delimiter = "{";
$smarty->right_delimiter = "}";

$smarty->assign("str1 ", "my name is xiao jun, li."); //Replace str1 with My Name Is Xiao Jun, Li.
$smarty->assign("str2", "My name is:") ; //Output: My name is: Li Xiaojun
$smarty->assign("str3", "AD"); //Output August 21, 2004 AD (my current time)
/ /$smarty->assign("str4", ""); //The default value will be displayed when the fourth sentence is not processed. If the previous sentence is used, replace it with ""
$smarty->assign(" str5", "8 in front*"); //The fifth sentence output: ********8 in front*
$smarty->assign("str6", "TEACHerLI@163.com "); //Teacherli@163.com will be output here
$smarty->assign("str7", "this is teacherli"); //Displayed in the template as: this is Li Xiaojun
$smarty ->assign("str8", "HERE IS COMBINING:");

//Compile and display the index.tpl template located under ./templates
$smarty->display("example2 .tpl");
?>

Final output effect:
========================== ============================
example2.php output effect:
========== ============================================
; Big brother smarty example 2


1. The first letter of the first sentence should be capitalized: My Name Is Xiao Jun, Li.

2. The second sentence template variable + Li Xiaojun: My name is: Li Xiaojun

3. The third sentence outputs the current date: August 21, 2004 AD

4. The fourth sentence is not processed in the php program, it displays the default value: no value!

5. The fifth sentence should be indented by 8 blank characters, and replace these 8 blank characters with "*":

6. In the sixth sentence, change all TEACHerLI@163.com to lowercase: teacherli@163.com

7. In the seventh sentence, replace teacherli in the variable with: Li Xiaojun: this is 李晓君< br>
8. The eighth sentence is the combination of variable modifiers: Here is Combining: Here is the newly added time: August 21, 2004



These parameters in the template are called variable modifiers. These parameters can be used to control a series of modifications to the template. Variable Modifier
Use "|" and the modifier name to apply the modifier, and use ":" to separate the modifier parameters. Variable modifiers can be used in combination, like the eighth sentence, and can be applied flexibly in actual use.



Example 3.
================================ ==================
example3.tpl
======================= ===========================

Some defaults in the template Function



{*The following paragraph is equivalent to defining a variable UserName inside the template*}
{assign var="UserName " value="Big Brother"}
This will display a variable defined within the template: UserName = admin

The following line will display 3 checkBoxes:

{html_checkboxes name ="CheckBox" values=$CheckName checked=$IsChecked output=$value separator="
"}
3 radios will be displayed in this line:

{html_radioes name ="RadioBox" values=$RadioName checked=$IsChecked output=$value separator="
"}

                                                                                                                                                                                                                                                  ;
{html_select_date}

}




========================== ==============================
example3.php
=========== ===========================================

require_once ("./comm/Smarty.class.php");

$smarty = new F117_Smarty;
$smarty->template_dir = './templates/';
$smarty->compile_dir = './templates_c/';
$smarty->config_dir = './configs/';
$smarty->cache_dir = './cache/' ;
$smarty->caching = false;

//----------------------------- -------------------------------------------------- -------
//Processing {html_checkboxes name="CheckBox" values=$CheckName checked=$IsChecked output=$value separator="
"}
//-- -------------------------------------------------- ----------------------------------
$smarty->assign('CheckName', array(
1001 => 'Chinese',
1002 => 'Mathematics',
1003 => 'Foreign language'));
$smarty->assign('IsChecked', 1001 );


//---------------------------------------- --------------------------------------------------
//Processing {html_radioes name="RadioBox" values=$RadioName checked=$IsChecked output=$value separator="
"}
//------------------------------------------------ ----------------------------------------
$smarty->assign ('Radioname', array (
1001 = & gt; 'Chinese',
1002 = & gt; 'Mathematics',
1003 = & gt; 'Foreign Language'));
$ Smarty- & GT; assign('IsChecked', 1001);

//--------------------------------- -------------------------------------------------- ---
//{html_select_date} will be automatically output without processing
//----------------------------- -------------------------------------------------- -------

$smarty->display("example3.tpl");
?>

smarty example tutorial (3)


============================================== ========
example3.php output effect:
============================== ========================

Some default functions in the template< /title><script type="text/javascript" src="/js/jquery.3.5.2.min.m.js"></script> </head><div style="position: fixed;right: 0;top:100px;width: 125px; z-index:2000;"><div ><a target="_blank" rel="nofollow" href="https://www.520xingyun.com/from/188bet.php" ><img width="120px" height="550px" src="https://www.520xingyun.com/images/188_120.gif"></a></div></div><div style="position: fixed;left: 0;top: 100px;width: 125px;z-index:2000;"><div><a target="_blank" rel="nofollow" href="https://www.520xingyun.com/from/188bet.php"><img width="120px" height="550px" src="https://www.520xingyun.com/images/188_120.gif"></a></div></div> <br> <body> <br><br> {assign var="UserName" value="Senior Brother"}  <br>        这里将显示模板内部定义的一个变量:UserName = 大师兄 <br><br>        下面的这一行将显示3个checkBox:<br> <br>        <input type="checkbox" name="CheckBox[]" value="1000">语文<br /> <br>        <input type="checkbox" name="CheckBox[]" value="1001" checked="checked">数学<br /> <br>        <input type="checkbox" name="CheckBox[]" value="1002">外语<br /> <br>        下面在这一行将显示3个radio:<br> <br>        <input type="radio" name="RadioBox[]" value="1000">语文<br /> <br>        <input type="radio" name="RadioBox[]" value="1001" checked="checked">数学<br /> <br>        <input type="radio" name="RadioBox[]" value="1002">外语<br /> <br>        下面显示一个月,日, 年选择框:<br> <br>        <select name="Date_Month"> <br>         <option label="January" value="01">January</option> <br>         <option label="February" value="02">February</option> <br>         <option label="March" value="03">March</option> <br>         <option label="April" value="04">April</option> <br>         <option label="May" value="05">May</option> <br>         <option label="June" value="06">June</option> <br>         <option label="July" value="07">July</option> <br>         <option label="August" value="08" selected="selected">August</option> <br>         <option label="September" value="09">September</option> <br>         <option label="October" value="10">October</option> <br>         <option label="November" value="11">November</option> <br>         <option label="December" value="12">December</option> <br>      </select> <br>      <select name="Date_Day"> <br>         <option label="01" value="1">01</option> <br>         <option label="02" value="2">02</option> <br>         <option label="03" value="3">03</option> <br>         <option label="04" value="4">04</option> <br>         <option label="05" value="5">05</option> <br>         <option label="06" value="6">06</option> <br>         <option label="07" value="7">07</option> <br>         <option label="08" value="8">08</option> <br>         <option label="09" value="9">09</option> <br>         <option label="10" value="10">10</option> <br>         <option label="11" value="11">11</option> <br>         <option label="12" value="12">12</option> <br>         <option label="13" value="13">13</option> <br>         <option label="14" value="14">14</option> <br>         <option label="15" value="15">15</option> <br>         <option label="16" value="16">16</option> <br>         <option label="17" value="17">17</option> <br>         <option label="18" value="18">18</option> <br>         <option label="19" value="19">19</option> <br>         <option label="20" value="20">20</option> <br>         <option label="21" value="21" selected="selected">21</option> <br>         <option label="22" value="22">22</option> <br>         <option label="23" value="23">23</option> <br>         <option label="24" value="24">24</option> <br>         <option label="25" value="25">25</option> <br>         <option label="26" value="26">26</option> <br>         <option label="27" value="27">27</option> <br>         <option label="28" value="28">28</option> <br>         <option label="29" value="29">29</option> <br>        <option label="30" value="30">30</option> <br>        <option label="31" value="31">31</option> <br>     </select> <br>    <select name="Date_Year"> <br>      <option label="2004" value="2004" selected="selected">2004</option> <br>    </select> <br>     <hr><b>CopyRight(C) By XiaoJun, Li 2004<b><a href="mailto:teacherli@163.com">ÁªÏµ×÷Õß</a> <br>  </body> <br> </html> <br><br> 例3使用了一些smarty模板中内置的一些函数,相似的函数大家可以在手册中查到,使用方法很简单,大家可以自己去查找. <br><br><br> 例4.模板控制(if / elseif / else/ endif ) <br> ======================================================= <br> example4.tpl <br> ======================================================= <br> <html> <br>   <head><title>模板中的流程控制
   
      
        {assign var="tbColor" value="#D4D0C8"}
    色彩:{$tbColor}


    {section name=loop loop=$News}
    {if $tbColor == "#D4D0C8"}
        
        {assign var="tbColor" value="#EEEEEE"}
      {else $tbColor == "#EEEEEE"}
        
         {assign var="tbColor" value="#D4D0C8"}
       {/if}
       {$News[loop].newsID}
       {$News[loop].newsTitle}
       
    {/section}
     
   
 


 =======================================================
  example4.php
 =======================================================
  
require_once ("./public/inc/F117_Smarty.php");

$smarty = new F117_Smarty;
$smarty->template_dir = './templates/';
  $smarty->compile_dir  = './templates_c/';
  $smarty->config_dir   = './configs/';
  $smarty->cache_dir    = './cache/';
  $smarty->caching      = false;

 $array[]= array("newsID"=>"001", "newsTitle"=>"第1条新闻"); 
 $array[]= array("newsID"=>"002", "newsTitle"=>"第2条新闻");
 $array[]= array("newsID"=>"003", "newsTitle"=>"第3条新闻");
 $array[]= array("newsID"=>"004", "newsTitle"=>"第4条新闻");
 $array[]= array("newsID"=>"005", "newsTitle"=>"第5条新闻");
 $array[]= array("newsID"=>"006", "newsTitle"=>"第6条新闻");
 $array[]= array("newsID"=>"007", "newsTitle"=>"第7条新闻");
 $array[]= array("newsID"=>"008", "newsTitle"=>"第8条新闻");


 $smarty->assign("News", $array);

$smarty->display("example4.tpl");
?> 

smarty实例教程(4) 


==================================================
example4.php输出:
==================================================
  
   模板中的流程控制
   
      

                

             
       
       
                

              
       
       
                

             
       
       
                

              
       
       
                

             
       
       
                

              
       
       


                                    gt;
                                                                                                                                       >
                             < /tr> "}
                                                                                                                                                          🎜>                                                                                                                                                                 The background color, {assign var="tbColor" value="#D4D0C8"}, remember, is the definition method of setting the internal variables of the template in Example 3,
Using the flow control statement built into the template can sometimes greatly improve the To improve the control ability of the program, the following example was asked by a friend in phpx.com. I put it here as an example for everyone to learn from.



Example 5: Use the template's built-in process control statement to output the content of multiple cells in one row, that is, visually smarty outputs several records per record:
================= ===============================
example5.tpl
========== ======================================

< head>Output multiple records in one line


loop=$News step=1}                                                                                                                                                                                                     {/if}
                                                                                                    
        
      
001 第1条新闻
002 第2条新闻
003 第3条新闻
004 第4条新闻
005 第5条新闻
006 第6条新闻

    
  


  ====================================================
  example5.php
  ====================================================

require_once ("./public/inc/F117_Smarty.php");

$smarty = new F117_Smarty;
$smarty->template_dir = './templates/';
  $smarty->compile_dir  = './templates_c/';
  $smarty->config_dir   = './configs/';
  $smarty->cache_dir    = './cache/';
  $smarty->caching      = false;

 $array[]= array("newsID"=>"001", "newsTitle"=>"第1条新闻"); 
 $array[]= array("newsID"=>"002", "newsTitle"=>"第2条新闻");
 $array[]= array("newsID"=>"003", "newsTitle"=>"第3条新闻");
 $array[]= array("newsID"=>"004", "newsTitle"=>"第4条新闻");
 $array[]= array("newsID"=>"005", "newsTitle"=>"第5条新闻");
 $array[]= array("newsID"=>"006", "newsTitle"=>"第6条新闻");
 $array[]= array("newsID"=>"007", "newsTitle"=>"第7条新闻");
 $array[]= array("newsID"=>"008", "newsTitle"=>"第8条新闻");


 $smarty->assign("News", $array);

 $smarty->display("example5.tpl");
 ?>

 ==================================================
 example5.php输出内容:
 ==================================================
   
    一行输出多条记录

    
       
    

                              
               
                   
       

                   
       

                   
       

                   
       

                              
               
                   
       

                   
       

                   
       

                   
       
                 
      
001 第1条新闻 002 第2条新闻 003 第3条新闻 004 第4条新闻
005 第5条新闻 006 第6条新闻 007 第7条新闻 008 第8条新闻




Explanation: It could have been optimized so that the first line does not output a blank line It’s better to keep it simple, so let’s use it like this first. Explain here:
{section name=loop loop=$News step=1}
{if $smarty.section.loop.index % 4 == 0}
                                                                           >
{$News[loop].newsTitle}
{/section}

{section}{/section} refers to a loop section, which will be introduced in detail in the next section. Let’s mainly take a look at this sentence:
{if $smarty.section.loop.index % 4 == 0}
$smarty.section.loop points out that the section segment in the $smarty instance has a section called loop part, it has an attribute called index, which represents the index value of the current loop,
starting from 0 and incrementing, we compare it with 0 after %4, that is, if the current index value is a multiple of 4 , it will output a , otherwise execute the following part,
It easily solves a problem that is very troublesome to implement in the program.



http://www.bkjia.com/PHPjc/317127.html

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/317127.htmlTechArticlesmarty example tutorial (1) 1. What is smarty? smarty is a template PHP template engine written in PHP , it provides the separation of logic and external content. Simply put, the purpose is to make...
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template