smarty example tutorial_PHP tutorial
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
======================== =======
body>
================================== ===================
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
=============================== =================
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:
========== ============================================
;
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
======================= ===========================
{*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:
============================== ========================
{assign var="UserName" value="Senior Brother"}
这里将显示模板内部定义的一个变量:UserName = 大师兄
下面的这一行将显示3个checkBox:
语文
数学
外语
下面在这一行将显示3个radio:
语文
数学
外语
下面显示一个月,日, 年选择框:
CopyRight(C) By XiaoJun, Li 2004ÁªÏµ×÷Õß
例3使用了一些smarty模板中内置的一些函数,相似的函数大家可以在手册中查到,使用方法很简单,大家可以自己去查找.
例4.模板控制(if / elseif / else/ endif )
=======================================================
example4.tpl
=======================================================
{$News[loop].newsID} | {$News[loop].newsTitle} |
=======================================================
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输出:
==================================================
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
{section name=loop loop=$News step=1}
{if $smarty.section.loop.index % 4 == 0}
>
{/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
It easily solves a problem that is very troublesome to implement in the program.
http://www.bkjia.com/PHPjc/317127.html

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7
