search
HomeBackend DevelopmentPHP Tutorialsmarty模板引擎基础知识入门_PHP

smarty模板引擎基础知识入门_PHP

May 31, 2016 am 11:45 AM
smartybasic knowledgetemplate engine

本文实例讲述了smarty模板引擎基础知识。分享给大家供大家参考。具体如下:

一、基本概念

1.什么是mvc?
mvc是一种开发模式,核心思想是:数据的输入、数据的处理、数据显示的强制分离。
2.什么是smarty?
smarty是一个php的模板引擎。更明确的来说,它可以帮助开发者更好的分离程序逻辑和页面显示。

3.smarty运行原理
模板文件,就是一个显示数据的模板,其中需要显示的数据用占位符代替。
smarty运行时,会读取模板文件,将模板文件中的占位符替换成真正的数据,并输出一个处理后的php文件,交由服务器运行。

二、自己写一个smarty模板

为了更好的理解smarty模板,现在自己先写一个自己的smarty模板-minismarty,让自己更加深入的了解smarty运行原理。

1.新建项目minismarty
新建模板文件路径:templates
新建模板文件被编译后的文件路径:templates_c
新建模板文件:intro.tpl
新建运行的文件:index.php
新建自己的smarty,即处理模板的文件:cls_MiniSmarty.php

2.编写index.php文件

<&#63;php 
  require_once './cls_MiniSmarty.php';
  $miniSmarty = new MiniSmarty();
  //传递数据
  $miniSmarty->assign("title","hello minismarty!");
  $miniSmarty->assign("content","<font color='red'>this is content!</font>");
  //传递数据到哪个页面显示
  $miniSmarty->display("intro.tpl");
&#63;>

3.编写intro.tpl文件

<!--这是个模板文件--> 
<html> 
<head> 
<meta http-equiv="Content-Language" content="en" />
<meta name="GENERATOR" content="PHPEclipse 1.0" />
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>{$title}</title>
</head>
<body bgcolor="#FFFFFF" text="#000000" link="#FF9966" vlink="#FF9966" alink="#FFCC99">
{$content}
</body>
</html>

这里面的内容是用占位符的形式,smarty的作用就是将占位符的内容替换成真正的数据。
这样就可以实现模板文件和数据文件强制分离,通过smarty进行数据的传递。

4.编写cls_MiniSmarty.php文件

<&#63;php 
/** 
 * 
 * 原本是通过smarty模板引擎给模板提供数据的 
 * 现在自己模仿写一个模板,给模板提供数据的类 
 * smarty运行时,读取模板文件,将模板文件替换成可运行的php文件
 * 服务器真正运行的文件是处理后的文件
 */ 
class MiniSmarty { 
  //模板文件路径 
  var $template_dir = "./templates/"; 
  //模板文件被替换后的文件路径 
  var $templates_c_dir = "./templates_c/"; 
  //存放变量值 
  var $tpl_vars = array (); 
  //主要模拟2个方法 
  /** 
   * 添加数据 
   * 参数1:键 
   * 参数2:值,默认为null 
   */ 
  function assign($tpl_var, $var = null) { 
    if ($tpl_var != '') { 
      $this->tpl_vars[$tpl_var] = $var; //将数据添加到数组中 
    } 
  } 
  /** 
   * 显示数据 
   * 参数1:显示到哪个模板文件中 
   */ 
  function display($tpl_file) { 
    //获得模板文件的路径 
    $tpl_file_path = $this->template_dir . $tpl_file; 
    //获得模板文件被编译后的文件路径 
    $compile_file_path = $this->templates_c_dir . "com_" . $tpl_file . ".php"; 
    //判断文件是否存在 
    if (!file_exists($tpl_file_path)) { 
      return false; 
    } 
    //不用每次都生成编译文件,只有编译文件不存在或者模板文件被修改了才生成新的编译文件 
    //相当于缓存了编译文件 
    //filemtime函数:获得文件的生成时间 
    if (!file_exists($compile_file_path) || filemtime($tpl_file_path) > filemtime($compile_file_path)) { 
      //读取模板文件的内容 
      $fpl_file_content = file_get_contents($tpl_file_path); 
      $newStr = myReplace($fpl_file_content); 
      //将替换后的字符串生成新的文件,也就是编译后的文件 
      file_put_contents($compile_file_path, $newStr); 
    } 
    //引入编译后的文件 
    include $compile_file_path; 
  } 
  /** 
   * 对模板文件中的内容进行替换,获得新的字符串 
   */ 
  function myReplace($fpl_file_content) { 
    $pattern = array ( 
      '/\{\s*\$([a-zA-Z_][a-zA-Z0-9_]*)\s*\}/i' 
    ); 
    $replace = array ( 
      '<&#63;php echo $this->tpl_vars["${1}"] &#63;>' 
    ); 
    $newStr = preg_replace($pattern, $replace, $fpl_file_content); 
    return $newStr; 
  } 
} 
&#63;>

preg_replace方法介绍:
参数1:替换的规则
参数2:替换成的内容
参数3:替换操作的内容

5.运行结果

标题和内容都显示出来了:

结论:

真正运行的文件,既不是index.php,也不是intro.php,而是二者通过smarty作用后的文件:
com_intro.tpl.php。这个文件中数据来源于index.php,显示的布局来自intro.tpl,中间的桥梁是smarty。
smarty的作用是接受数据、填充数据(替换模板中的占位符)、并加载替换后的文件。

三、讲解smarty使用细节

1.如何配置smarty?

解压后,将libs文件夹拷贝到项目目录下即可,然后再创建2个文件夹templates和templates_c,分别放模板文件和模板编译后文件。

2.使用smarty注意事项

①替换变量的标示符。
因为默认的表示符是{}这个和style样式中的{}发生冲突,所以需要修改一下默认的标识符,一般修改为:{}
②修改标识符的方法。
方法一:直接修改smarty类源码:不推荐。
方法二:使用smarty提供的方法进行修改。

$smarty->left_delimiter="{<";
$smarty->right_delimiter=">}";

③smarty的一些基本配置

$smarty->template_dir="./templates";//模板路径
$smarty->compile_dir="./templates_c";//编译路径
$smarty->caching=false;  //是否使用缓存
$smarty->cache_dir="./smarty_cache";//如果使用缓存的话:缓存的路径

3.smarty模板技术分配变量的细节问题

一句话:可以分配php支持的各种数据。
php基本数据:int double string bool
复合数据类型:array object
特殊数据类型:resource null

希望本文所述对大家的php程序设计有所帮助。

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Explain how load balancing affects session management and how to address it.Explain how load balancing affects session management and how to address it.Apr 29, 2025 am 12:42 AM

Load balancing affects session management, but can be resolved with session replication, session stickiness, and centralized session storage. 1. Session Replication Copy session data between servers. 2. Session stickiness directs user requests to the same server. 3. Centralized session storage uses independent servers such as Redis to store session data to ensure data sharing.

Explain the concept of session locking.Explain the concept of session locking.Apr 29, 2025 am 12:39 AM

Sessionlockingisatechniqueusedtoensureauser'ssessionremainsexclusivetooneuseratatime.Itiscrucialforpreventingdatacorruptionandsecuritybreachesinmulti-userapplications.Sessionlockingisimplementedusingserver-sidelockingmechanisms,suchasReentrantLockinJ

Are there any alternatives to PHP sessions?Are there any alternatives to PHP sessions?Apr 29, 2025 am 12:36 AM

Alternatives to PHP sessions include Cookies, Token-based Authentication, Database-based Sessions, and Redis/Memcached. 1.Cookies manage sessions by storing data on the client, which is simple but low in security. 2.Token-based Authentication uses tokens to verify users, which is highly secure but requires additional logic. 3.Database-basedSessions stores data in the database, which has good scalability but may affect performance. 4. Redis/Memcached uses distributed cache to improve performance and scalability, but requires additional matching

Define the term 'session hijacking' in the context of PHP.Define the term 'session hijacking' in the context of PHP.Apr 29, 2025 am 12:33 AM

Sessionhijacking refers to an attacker impersonating a user by obtaining the user's sessionID. Prevention methods include: 1) encrypting communication using HTTPS; 2) verifying the source of the sessionID; 3) using a secure sessionID generation algorithm; 4) regularly updating the sessionID.

What is the full form of PHP?What is the full form of PHP?Apr 28, 2025 pm 04:58 PM

The article discusses PHP, detailing its full form, main uses in web development, comparison with Python and Java, and its ease of learning for beginners.

How does PHP handle form data?How does PHP handle form data?Apr 28, 2025 pm 04:57 PM

PHP handles form data using $\_POST and $\_GET superglobals, with security ensured through validation, sanitization, and secure database interactions.

What is the difference between PHP and ASP.NET?What is the difference between PHP and ASP.NET?Apr 28, 2025 pm 04:56 PM

The article compares PHP and ASP.NET, focusing on their suitability for large-scale web applications, performance differences, and security features. Both are viable for large projects, but PHP is open-source and platform-independent, while ASP.NET,

Is PHP a case-sensitive language?Is PHP a case-sensitive language?Apr 28, 2025 pm 04:55 PM

PHP's case sensitivity varies: functions are insensitive, while variables and classes are sensitive. Best practices include consistent naming and using case-insensitive functions for comparisons.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.