Smarty instance tutorial (4)

Source: Internet
Author: User
Tags constant definition
Starting from this section, we will learn how to apply Smarty to the actual example. for demonstration purposes, I will use a previously written website as an instance. first, let me explain that my art skills are not very strong, so the pages I designed are not very nice. let's take a look at them.

Starting from this section, we will learn how to apply Smarty to the actual example. for demonstration purposes, I will use a previously written website as an instance. first, let me explain that my art skills are not very strong, so the pages I designed are not very nice. let's take a look at them.
Before reading this document, you can first look at indexbak.htmand newsbak.htm, which are the example diagrams we have generated.

I. First, let's explain the database we are going to use. below I will first give you the database source file for example:


========================================================== ====================
Create database News;

USE News;

/****************************
*
* Table name: tb_news_ch
* Usage: domestic news table
*
****************************/
Create table tb_news_ch
(
INewsID interger (11) primary key auto_increment,
VcNewsTitle varchar (50) not null,
LtNewsContent longtext not null
);


/****************************
*
* Table name: tb_news_in
* Usage: international news table
*
****************************/
Create table tb_news_in
(
INewsID interger (11) primary key auto_increment,
VcNewsTitle varchar (50) not null,
LtNewsContent longtext not null
);


/****************************
*
* Table name: tb_news_mu
* Usage: Entertainment News table
*
****************************/

Create table tb_news_mu
(
INewsID interger (11) primary key auto_increment,
VcNewsTitle varchar (50) not null,
LtNewsContent longtext not null
);
========================================================== ======================

Database description.

First question:
We can see that the field names of the three data tables are the same, so why not combine them into a data table? the answer is simple: efficiency, during development, we may not feel any improvement in efficiency. However, when the website runs for a period of time, its news data volume will become very large, in addition, if the website becomes larger in the future, all types may be separated to form a website similar to china.xxx.com, international.xxx.com, and music.xxx.com, and each column will be separately divided into physical sites, at that time, if news is still put together, it will lead to database bottlenecks. Therefore, it is reasonable to separate the current sites.

Second question:
Someone may ask, what is the I, vc, and lt used before the field? The name is based on the field type, which is also a good style. you can know the type of a field by placing the type prefix before the variable, this is a reference from Microsoft's Hungary naming method. During database design, I first defined each type as 1-3 letters, then add the corresponding code before each field to represent its type. as shown in the preceding figure, the field types of each database are defined:

Integer I
Varchar vc
Longtext lt
Char c
....

In use,

II. sample site directory structure:

PHP code :--------------------------------------------------------------------------------
+ Web (site root directory)
|
| ---- + Comm (Smarty Documentation Directory)
|
| ---- + Plugins (Smarty plug-in directory)
| ----- Config_File.class.php (Smarty configuration file)
| ----- Smarty. class. php (master Smarty file)
| ----- Smarty_Compiler.class.php (Smarty compilation class file)
|
| ---- + Cache (Smarty cache directory, which guarantees read and write permissions under * nix)
|
| ---- + Templates (website template file storage directory)
|
| ---- Header. tpl (page header template file)
| ---- Index. tpl (website homepage template file)
| ---- Foot. tpl (page footer template file)
| ---- News. tpl (news page template file)
|
|
| ---- + Templates_c (directory for storing template files after compilation, and read/write permission for * nix)
|
| ---- + Css (site CSS file directory)
|
| ---- + Image (site image directory)
|
| ---- + Media (website Flash animation storage directory)
|
| ----Indexbak.htm (original homepage)
|
| ---- Newsbk, htm (original news page)
|
| ---- Index. php (Smarty homepage program file)
|
| ---- News. php (Smarty news display file)
|
| ------Example .txt (Directory Description)
|
| ------Data warehouse creation file .txt (database creation document)

For details, download the instance and compare the structure.

--------------------------------------------------------------------------------

III. instance fragments in the template:

1. index. tpl:

Index. tpl is the template class of the site homepage. after opening its source file, we can see the following two sentences:


========================================================== ============
1. <{* The following sentence is the page header of this page *}>
2. <{include file = "header. tpl"}>
========================================================== ============

The first sentence is a template comment.
The first sentence indicates that another file is to be included in the current position. what file? header. tpl, the header here. tpl is the standard page header file of the page. it is used to separate this part so that it can be reused on other pages. Traditionally, you should write the page header file in a table, however, some of my instances are not compliant with the specifications.

Let's look at the last sentence:

========================================================== ==========
3. <{include file = "foot. tpl"}>
========================================================== ==========

Needless to say, everyone understands that it contains a footer file.

Let's take a look at the template code of the domestic news section:


========================================================== ==========







<{Section name = loop = $ News_CH}>
  • "Class =" newsfont "> <{$ News_CH [loop]. NewsTitle}>
    <{/Section}>

  • ========================================================== ==========

    For more information, see <{section}> and <{/section}>. the other parts are listed to better understand the meaning of the code. Can you see it? Here, I will review the previous content: I have defined a section loop template block named loop, which loops through the $ News_CH array, A link will be generated for the current news at news. php? Type = 1 & id = xxx. here, xxx is the extracted iNewsID from the database. it refers to the news with id to be displayed on the news display page. $ News_CH [loop]. does NewsTitle understand this representation? If you don't understand it, take a look at the <{section}> syntax in the "Smarty instance teaching-program design" section described in the previous section.
    You may feel a little unfamiliar with <{}>. here, <{}> defines blocks for template statements. we use {} in the first two sections, but this is a specific application, so we will not take {}, which is expressed by <{}> that everyone is used to. of course, this is in. in the php file.

    Let's look at the code for international news and entertainment news:

    PHP code:
    --------------------------------------------------------------------------------
    International news:

    ========================================================== ==========






    <{Section name = loop = $ News_IN}>
  • "Class =" newsfont "> <{$ News_IN [loop]. NewsTitle}>
    <{/Section}>

  • ========================================================== ==========

    Entertainment news:

    ========================================================== ==========






    <{Section name = loop = $ News_MU}>
  • "Class =" newsfont "> <{$ News_MU [loop]. NewsTitle}>
    <{/Section}>

  • ========================================================== ==========

    --------------------------------------------------------------------------------

    Are there any differences? The loop part is different. The loop refers to the array to be cyclic. Note that the loop of multiple sections cannot be specified as the same value, in this case, the Smarty analysis template analyzes two sections with the same name at the same time and generates two identical records.

    When you see this, someone will have a question: I already have a loop block. how can I display it in the current position only the number of records we want? This problem is simple. we control the number of cycles of the section loop block of Smarty in the. php file to replace the array of the loop block. we don't need to consider it when designing the template.

    <{$ NewsTitle}> ---- Tianyao Information Network

    The title of the news page to be displayed is the news title + "---- Tianyao Information Network"
    2. news Title:




    <{$ NewsTitle}>

    Here, a template variable $ NewsTitle is set to replace $ NewsTitle (including the title bar) with the title of the current news in the database.
    3. news content:

    <{$ NewsContext}>

    This sentence is also easy to show news content in the current position.

    Of course, here we will simply list the news. in actual applications, you can also list the source, posting time, author, and related news of the article, I will not discuss it much here.


    III. Procedure:

    1. let's take a look at the index. php source file, and then let's analyze its role slowly:


    ========================================================== ============================
    Index. php
    ========================================================== ============================

    Php code:

     

    For convenience, I marked every place to be noted. The following describes the role of each part:

    1. Program comments and style issues. I have added this to the program many times to help readers develop this habit.
    2. file inclusion. this sentence means to include the Smarty class file into the current program file.
    3. constant definition: defines NUM as 5, which is the number of news entries
    4. set the Smarty parameter: For more information about the parameters, see the previous section. here, we only want to describe the $ smarty-> cache attribute. during the program debugging process, to set it to false, we can implement the program cache effect by designing it to true upon official release.
    5. database connection: do I have to say this part? Standard PHP statement.
    6. search for SQL statements in Chinese news: Standard SQL statements are sorted in descending order by new question numbers.
    7. while ():
    This statement controls the number of news lines to be displayed. first, assign a value to $ I as NUM, and NUM as a constant defined outside of the start. use the $ I> 0 condition in the start judgment of while (), while () in each loop, the value of $ I is reduced by 1, so that when it completes five cycles, while will end.
    Here we mainly look at the $ array [] array:
    $ Array [] is theoretically a two-dimensional array, that is, the element in an array is another array. in the preceding example, when the while () statement ends, $ array is an array containing five array elements, and each element is an array of character indexes. these character indexes define the attribute value of $ news [loop] of the section loop block in the template. you must note that the attribute value corresponds to the attribute value of the template loop block, otherwise, it cannot be displayed!
    When constructing this two-dimensional array, we use a substr () method to intercept characters. this method is for reference only. in actual use, because Chinese characters are full-width characters, using it may cause garbled characters. in future examples, we will use another netizen and the csubstr () function to implement the character truncation function.

    8. parse the section loop block of loop = $ News_CH in the template.
    Note that when $ smarty-> assign ("News_CH", $ array) is used, the first parameter of assign is the value of loop in section, the second parameter is the array created above.

    9. deregister $ array: $ array [] after use, it must be deregistered, because $ array is not cleared when a value is assigned to $ array using the value assignment statement, instead, the new array is added as an element of it. to avoid side effects, it is necessary to use unset () here.

    10. International news processing module:
    Like the domestic news processing module, you can compare the template with this section to find out what is related to it.

    11. entertainment news processing module: Same as above, we look for relationships among them. I believe you will have some gains after reading them.

    12. process and display index. tpl.


    1.
    /*************************************** ******
    *
    * File name: index. php
    * For use: Display instance programs
    *
    * Author: Master
    * Email: teacherli@163.com
    *
    **************************************** *****/
    2. include_once ("./comm/Smarty. class. php"); // contains the smarty class file
    3. define ("NUM", 5); // defines the number of news entries displayed each time.

    4. $ smarty = new Smarty (); // Create a smarty instance object $ smarty
    $ Smarty-> templates_dir = "./templates"; // set the template directory
    $ Smarty-> compile_dir = "./templates_c"; // Set the compilation Directory
    $ Smarty-> cache_dir = "./cache"; // you can specify a cache directory.
    $ Smarty-> cache_lifetime = 60*60*24; // you can specify the cache time.
    $ Smarty-> caching = false; // set this parameter to false during debugging. use true for release.
    $ Smarty-> left_delimiter = "<{"; // you can specify the left boundary.
    $ Smarty-> right_delimiter = "}>"; // you can specify the right boundary.


    5. $ db = mysql_connect ("localhost", "root ","");
    Mysql_select_db ("News", $ db );


    // The domestic news section will be processed here
    6. $ strQuery = "SELECT iNewsID, iNewsTitle FROM tb_news_CH order by iNewsID DESC ";
    $ Result = mysql_query ($ strQuery );
    $ I = NUM;
    7. while ($ row = mysql_fetch_array ($ result) & $ I> 0)
    {
    $ Array [] = array ("NewsID", substr ($ row ["iNewsID"], 0, 40 ),
    "NewsTitle", substr ($ row ["vcNewsTitle"], 0, 40 ));

    $ I --;
    }
    8. $ smarty-> assign ("News_CH", $ array );
    9. unset ($ array );
    Mysql_free_result ();


    10. // process the international news section here
    $ StrQuery = "SELECT iNewsID, iNewsTitle FROM tb_news_IN order by iNewsID DESC ";
    $ Result = mysql_query ($ strQuery );
    $ I = NUM;
    While ($ row = mysql_fetch_array ($ result) & $ I> 0)
    {
    $ Array [] = array ("NewsID", substr ($ row ["iNewsID"], 0, 40 ),
    "NewsTitle", substr ($ row ["vcNewsTitle"], 0, 40 ));

    $ I --;
    }
    $ Smarty-> assign ("News_IN", $ array );
    Unset ($ array );
    Mysql_free_result ();


    11. // The entertainment news section will be processed here
    $ StrQuery = "SELECT iNewsID, iNewsTitle FROM tb_news_MU order by iNewsID DESC ";
    $ Result = mysql_query ($ strQuery );
    $ I = NUM;
    While ($ row = mysql_fetch_array ($ result) & $ I> 0)
    {
    $ Array [] = array ("NewsID", substr ($ row ["iNewsID"], 0, 40 ),
    "NewsTitle", substr ($ row ["vcNewsTitle"], 0, 40 ));

    $ I --;
    }
    $ Smarty-> assign ("News_MU", $ array );
    Unset ($ array );
    Mysql_free_result ();


    Mysql_close ($ db );

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

    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.