Samrty quick start tutorial + instance

Source: Internet
Author: User

Smarty

 

 

 

Configuration:

<? PHP

/**

*

* @ Version $ ID: index. php

* @ Package

* @ Author www.php100.com

* @ Action: display the instance Program

*/

Include_once ("./smarty. Class. php"); // contains the smarty class file

 

$ Smarty = new smarty (); // create a smarty Instance Object $ smarty

$ Smarty-> templates ("./templates"); // you can specify the template directory.

$ Smarty-> templates_c ("./templates_c"); // you can specify the compiling directory.

$ Smarty-> cache ("./cache"); // cache directory

$ Smarty-> cache_lifetime = 0; // Cache Time

$ Smarty-> caching = true; // cache Method

 

$ Smarty-> left_delimiter = "{#";

$ Smarty-> right_delimiter = "#}";

$ Smarty-> assign ("name", "zaocha"); // replace template Variables

$ Smarty-> display ("index.htm"); // compile and display the index.htm Template under./templates

?>

 

 

Ii. Explain the smarty Program

 

As we can see, the smarty program is actually a set of code that complies with the PHP language specification. Let's explain it one by one:

1:/**/statement:

The included part is the program header annotation. The main content should be a brief introduction to the role of the program, copyright and the author and the writing time, which is not necessary in the smarty, but in terms of the program style, this is a good style.

 

2: include_once statement:

It includes the smarty file installed on the website to the current file. Note that the included path must be correctly written.

 

3: $ smarty = new smarty ():

This statement creates a smarty object $ smarty, which is a simple Object Instantiation.

 

4: $ smarty-> templates (""):

This statement specifies the path for the $ smarty object to use the TPL template. It is a directory. If this statement is not provided, the default template path of smarty is the templates directory of the current directory, when writing a program, we need to write this statement, which is also a good program style.

 

.

 

5: $ smarty-> templates_c (""):

This statement specifies the directory when the $ smarty object is compiled. In the template design article, we already know that smarty is a compilation template language, and this directory is the directory for compiling the template. Note that if the site is on a Linux server, make sure that

 

This directory defined in teamplates_c has writable and readable permissions. By default, its compiling directory is templates_c under the current directory. For the same reason, we will write it clearly.

 

6: $ smarty-> left_delimiter and $ smarty-> right_delimiter :== custom delimiter:

Specifies the Left and Right delimiters when searching for template variables. The default values are "{" and "}", but in practice, because we want to use <SCRIPT> in the template, the function definition in the script will inevitably use {}, although it has its own solution, we are used to redefining it.

 

For "{#" and "#}" or "<! -- {"And"} --> "or other specifiers. Note that if the Left and Right separators are defined here, in the template file, each variable must use the same symbol as the definition. For example, if you specify "<{" and "}>" here

 

Change {$ name} to <{$ name}> so that the program can find the template variables correctly.

7: $ smarty-> cache ("./cache "):

Tell the Template File Cache location output by smarty. In the previous article, we learned that the biggest advantage of smarty is that it can be cached. Here, we set the cache directory. By default, it is the cache directory under the current directory, which is equivalent to the templates_c directory.

 

Make sure it is readable and writable.

 

8: $ smarty-> cache_lifetime = 60*60*24:

 

Here, the effective cache time is calculated in seconds. When the first cache time expires, when the caching variable of smarty is set to true, the cache will be rebuilt. When the value is-1, it indicates that the created cache never expires. If it is 0, it indicates that the cache is slow every time the program is executed.

 

The storage is always re-created. The preceding settings indicate that cache_lifetime is set to one day.

 

9: $ smarty-> caching = 1:

This attribute tells smarty whether to cache and how to cache it. It can take three values, 0: smarty default value, indicating that the template is not cached; 1: indicates that smarty will use the current defined cache_lifetime to determine whether to end the cache; 2: indicates

 

Smarty uses the cache_lifetime value when the cache is created. Traditionally, true and false are used to indicate whether the cache is performed.

 

10: $ smarty-> assign ("name", "zaocha "):

The prototype of this number is assign (string varname, mixed var), varname is the template variable used in the template, and VAR indicates the variable name to replace the template variable; the second prototype is assign (mixed var). We will explain in detail how to use this member function in the following example. Assign is one of the core functions of smarty, all replace template variables must use it.

 

11. $ smarty-> display ("index. TPL "):

Display (string varname) is used to display a template. To put it simply, it displays the templates that have been analyzed and processed. The template file here does not need to be added with a path. You only need to use a file name, the path is defined in $ smarty-> templates (string path.

After the program is executed, we can open the templates_c and cache directories under the current directory, and we will find that there are more % directories below, which are the compilation and cache directories of smarty, it is automatically generated by the program. Do not directly modify these generated files.

I briefly introduced some common basic elements in the smarty program. In the following example, you can see that they will be used multiple times.

 

Syntax:

 

Template call, index. php:

Smarty-> assign ("template variable", "value (array/variable )");

$ Smarty-> display ("Template Name ");

Example:

 

$ Smarty-> assign ("name", "PhP100 Chinese site"); // you can replace the template variables with $ name.

$ Smarty-> display ("index.htm"); // This file is a template file and should be displayed in the template directory.

 

Introduction:

Three import modes:

{Include file = "header.htm "}

 

{Include file = "D:/www/head.htm "}

 

{Include fileenders 'head.htm' Title = "Main Menu "}

 

Judgment:

{If $ name = 'OK '}

 

{Else}

 

{/If}

 

 

 

Loop:

For one-dimensional arrays: Frequently Used

======= No key-value Array

{Foreach from = $ name item = ID}

ID: {$ id} <br>

{/Foreach}

 

======= An array with key values

{Foreach key = J item = V from = $ name}

{$ J }:{$ v} <br>

{/Foreach}

-- ********* Item: Content {key value}, key: key value, from: Array

Manual explanation:

Foreach is another solution for processing loops except section (different solutions are selected based on different needs ).

Foreach is used to process a simple array (the element types in the array are the same). Its format is much simpler than that of Section. The disadvantage is that it can only process a simple array.

Foreach must be used in pairs with/foreach, And the from and item attributes must be specified.

The name attribute can be arbitrarily specified (a combination of letters, numbers, and underscores ).

Foreach can be nested, but it must be unique in the nested foreach name.

The from attribute (usually an array) determines the number of cycles.

The foreachelse statement is executed when the from variable has no value.

 

 

 

For two-dimensional arrays:

 

{Section name = s loop = $ Stu}

 

{$ STU [s]. name}

 

{Sectionelse}

 

NO content

 

{/Section}

------********

Name: section name. $ is not required. It is equivalent to creating a new index for a two-dimensional array.

$ Loop: The variable to be recycled. You must use assign to operate the variable in the program.

 

Manual explanation:

The section of the template is used to traverse the data in the array. The section label must appear in pairs. The name and loop attributes must be set.

The name can be any combination of letters, numbers, and underscores. It can be nested, but the nested name must be unique. The variable loop (usually an array) determines the number of times the loop is executed.

When a variable needs to be output in a section loop, the name variable. sectionelse must be added to the variable and executed when the loop variable has no value.

 

Output: {$ name}

Use the {} delimiter to implement PHP-like

<? PHP?> Tag Functions

 

 

 

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)

 

 

 

Connection to the database:

 

Smarty_inc.php is a file that introduces samrty. Similarly, a class file should be configured for the database; mysql_inc.php

The template is powerful in connecting to data, reading data, and processing output results cyclically.

Index. php code:

Include ("smarty_inc.php ");

Include ("mysql_inc.php ");

 

$ Conn = db_connect ($ H, $ P, $ U, $ dB );

Mysql_query ("set names 'utf8 '");

 

 

$ SQL = "select ID, board_name, board_desc from boards ";

$ Res = mysql_query ($ SQL );

 

If (mysql_num_rows ($ res )){

While ($ ROW = mysql_fetch_array ($ res )){

$ Time = $ row ['id'];

$ Array [] = array ('id' => $ row ['id'], 'bname' => $ row ['board _ name'], 'bdesc' => $ row ['board _ desc']);

}

}

$ Smarty-> assign ("name", $ array); // replace template Variables

$ Smarty-> display ("index.htm"); // compile and display the index.htm Template under./templates

 

 

--*************************************** **************************

Reflection: How to Learn templates:

1) configuration: the configuration file is actually the process of introducing the template: Note: whether the path of the imported file is correct or not, the basic parameter settings of the template, instantiate

2) The use of templates is mainly a syntax class. Like the PHP language, it also has its own processing mechanism. Similar to PhP, there are four points: introduction, judgment, and loop, output the syntax knowledge of the four basic classes

3) connect to the data, read the data, and display the output

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.