Smarty half-hour quick start tutorial_PHP tutorial
Smarty’s programming part:
In the template design part of smarty, I briefly introduced some common settings of smarty in the template. This section mainly introduces how to start our process in smarty
Program design.
PHP code:-------------------------------------------------- ----------------------------------
First, let’s introduce some elements in the .php file we used in the previous section. Similarly, let’s take the index.php file at the beginning of the previous section to illustrate:
================================================== =
index.php
================================================
/*********************************************
*
* File name: index.php
* Function: Display example program
*
**********************************************/
include_once("./comm/Smarty.class.php"); //Include smarty class files
$smarty = new Smarty(); //Create smarty instance object $smarty
$smarty->templates("./templates"); //Set template directory
$smarty->templates_c("./templates_c"); //Set the compilation directory
//****Attention everyone, I am the new member here****//
$smarty->cache("./cache"); //Set the cache directory
$smarty->cache_lifetime = 60 * 60 * 24; //Set cache time
$smarty->caching = true; //Set caching method
//--------------------------------------------- -------
//The left and right boundary characters, the default is {}, but in actual application it is easy to use JavaScript
//Conflict, so it is recommended to set it to or other.
//------------------------------------------------ ----
$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");
?>
We can see that the program part of smarty is actually a set of codes that conform to the PHP language specification. Let’s explain them in turn:
1. /**/Statement:
The included part is the program header comments. The main content should be a brief introduction to the function of the program, copyright, author and writing time. This is not necessary in smarty
Necessary, but in terms of program style, this is a good style.
2. include_once statement:
It will include the smarty file installed on the website into the current file. Note that the included path must be written correctly.
3. $smarty = new Smarty():
This sentence creates a new Smarty object $smarty, which is a simple instantiation of an object.
4. $smarty->templates(""):
This sentence specifies the path when the $smarty object uses the tpl template. It is a directory. Without this sentence, Smarty's default template path is templates
Directory, when actually writing a program, we need to specify this sentence. This is also a good programming style.
5. $smarty->templates_c(""):
This sentence specifies the directory where the $smarty object is compiled. In the template design chapter, we already know that Smarty is a compiled template language, and this directory is what it compiles
Template directory, please note here that if the site is located on a *nix server, please ensure that the directory defined in teamplates_c has writable and readable permissions. By default, its compilation directory
is templates_c in the current directory. For the same reason, we write it out explicitly.
6. $smarty->left_delimiter and $smarty->right_delimiter:
Specifies the left and right separators when looking for template variables. By default, it is "{" and "}", but in practice, because we need to use <script> in the template, the function in Script is defined </script>
It is inevitable to use {}. Although it has its own solution, it is customary for us to redefine it as "" or "" or other identifiers, please note that if
hereAfter defining the left and right separators, each variable in the template file must use the same symbol as the definition. For example, it is specified as "" here, and it must also be used in the tpl template. The corresponding will be
{$name} becomes so that the program can correctly find the template variable.
7. $smarty->cache("./cache"):
Tell Smarty where to cache the output template files. In the previous article, we knew that the biggest advantage of Smarty is that it can be cached. Here is the directory where the cache is set. Default sentiment
In this case, it is the cache directory in the current directory, which is equivalent to the templates_c directory. In *nix systems, we must ensure that it is readable and writable.
8. $smarty->cache_lifetime = 60 * 60 * 24:
The cache validity time will be calculated in seconds. The cache will be rebuilt when the Smarty cache variable is set to true when the first cache time expires. When its
A value of -1 means that the created cache never expires, and a value of 0 means that the cache is always re-established every time the program is executed. The above setting means setting cache_lifetime to one day.
9. $smarty->caching = 1:
This property tells Smarty whether to cache and how to cache. It can take 3 values, 0: Smarty default value, indicating that the template will not be cached; 1: indicating
Smarty will use the currently defined cache_lifetime to decide whether to end the cache; 2: Indicates that Smarty will use the cache_lifetime value when the cache is created. It is customary to use
Use true and false to indicate whether to cache.
10. $smarty->assign("name", "李晓君"):
The prototype of this number is assign(string varname, mixed var), varname is the template variable used in the template, var indicates the variable name to be replaced by the template variable; its
The second prototype is assign(mixed var). We will explain the use of this member function in detail in the following examples. assign is one of the core functions of Smarty. All changes to templates
Use it for any amount of substitution.
11. $smarty->display("index.tpl"):
The prototype of this function is display(string varname), which is used to display a template. To put it simply, it will display the analyzed and processed templates. The template files here are not
To add a path, just use a file name. We have already defined its path in $smarty->templates(string path).
After the program is executed, we can open the templates_c and cache directories in the current directory, and we will find that there are some more %% directories below. These directories are Smarty’s compilation and
The cache directory is automatically generated by the program. Do not modify these generated files directly.
Above I briefly introduced some commonly used basic elements in Smarty programs. In the following examples, you can see that they will be used multiple times.
Next, we introduce a section loop block and a foreach loop block. Originally they should belong to the template part, but because they are the essence of smarty, and they are closely related to smarty programming
Some of them are very closely related, so I will talk about them separately in this section.
1. foreach: used to loop simple arrays. It is a selective section loop. Its definition format is:
{foreach from=$array item=array_id}
{foreachelse}
{/foreach}
Among them, from indicates the array variable to be looped, item is the name of the variable to be looped, and the number of loops is determined by the number of array variables specified by from. {foreachelse} is used as
How to handle when the array passed in the program is empty, here is a simple example:
===========================================
example6.tpl
===========================================
An array will be output here:
{foreach from=$newsArray item=newsID}
News number: {$newsID}
News content: {$newsTitle}
{foreachelse}
Sorry, there is no news output in the database!
{/foreach}
==========================================
example6.php
==========================================
/*********************************************
*
* File name: example6.php
* Function: Display example program 2
**********************************************/
include_once("./comm/Smarty.class.php");
$smarty = new Smarty();
$smarty->templates("./templates");
$smarty->templates_c("./templates_c");
$smarty->cache("./cache");
$smarty->cache_lifetime = 0;
$smarty->caching = true;
$smarty->left_delimiter = "{";
$smarty->right_delimiter = "}";
$array[] = array("newsID"=>1, "newsTitle"=>"News No. 1");
$array[] = array("newsID"=>2, "newsTitle"=>"News No. 2");
$array[] = array("newsID"=>3, "newsTitle"=>"News No. 3");
$array[] = array("newsID"=>4, "newsTitle"=>"News No. 4");
$array[] = array("newsID"=>5, "newsTitle"=>"News No. 5");
$array[] = array("newsID"=>6, "newsTitle"=>"News No. 6");
$smarty->assign("newsArray", $array);
//Compile and display the index.tpl template located under ./templates
$smarty->display("example6.tpl"

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python are both high-level programming languages that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values and handle functions that may return null values.


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

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version
Visual web development tools

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

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version
Useful JavaScript development tools