19.4 use Smarty
To use Smarty, you only need to make the Smarty class library available in the execution script. Generally, the require () statement is used:
Then, you can instantiate the Smarty class:
There is only so much work to start using this feature. The following is a simple example. Code List 19-3 provides a simple design template. Note that the template has two variables: $ title and $ name. Both variables are placed in braces, which are the default delimiters of Smarty. These delimiters tell Smarty to perform certain operations on the Content surrounded by delimiters. In this example, the only action is to replace the variable with the corresponding value passed in through the application logic (code listing 19-4. However, you will soon see that Smarty can complete a large number of other tasks, such as executing the presentation logic and modifying the text format.
Code List 19-3 simple Smarty design template (templates/welcome. tpl)
Note that Smarty wants this template to be In the templates directory, unless the template directory is modified through $ template_dir.
Code List 19-4 shows the corresponding application logic, which passes the appropriate variable value into the Smarty template.
Code List 19-4 index. tpl template application logic
The output result is 19-1.
This basic example shows that Smarty can completely separate the Web application logic layer from the presentation layer. However, this is just a glimpse of all the feature sets of Smarty. Before entering other topics, it is necessary to formally introduce the display () method used to obtain and display the Smarty template in the notebook. This method is used in Smarty-based scripts because it is used to obtain and display templates referenced by templates. The format is:
Figure 19-1 Output of code listing 19-4
The optional parameter cache_id specifies the name of the cache identifier, which will be discussed in section 19.8. The other optional parameter compile_id is used to maintain multiple caches on the same page. Multiple caches are stored in 19.8.3 .