Home Backend Development PHP Tutorial 菜鸟学PHP之Smarty入门(组图)_PHP

菜鸟学PHP之Smarty入门(组图)_PHP

Jun 01, 2016 pm 12:25 PM
smarty getting Started variable us stencil program rookie

SMARTY


  刚开始接触模版引擎的 PHP 设计师,听到 Smarty 时,都会觉得很难。其实笔者也不例外,碰都不敢碰一下。但是后来在剖析 XOOPS 的程序架构时,开始发现 Smarty 其实并不难。只要将 Smarty 基础功练好,在一般应用上就已经相当足够了。当然基础能打好,后面的进阶应用也就不用怕了。
  
  这篇文章的主要用意并非要深入探讨 Smarty 的使用,这在官方使用说明中都已经写得很完整了。笔者仅在此写下一些自己使用上的心得,让想要了解 Smarty 却不得其门而入的朋友,可以从中得到一些启示。就因为这篇文章的内容不是非常深入,会使用 Smarty 的朋友们可能会觉得简单了点。
  
  目前本文已经第三次修订了,本想多加一些料进来;不过碍于时间的关系,很多 Smarty 的进阶技巧笔者并没有研究得很透彻,所以也不敢拿出来现眼,但笔者相信这篇文章应该能够满足大多数想学习 Smarty 的初学者了。当然本文有谬误的地方也欢迎告知,笔者会在下一次的修订中更正的。
  
  Smarty介绍
  
  什么是模版引擎

  
  不知道从什么时候开始,有人开始对 HTML 内嵌入 Server Script 觉得不太满意。然而不论是微软的 ASP 或是开放源码的 PHP,都是属于内嵌 Server Script 的网页伺服端语言。因此也就有人想到,如果能把程序应用逻辑 (或称商业应用逻辑) 与网页呈现 (Layout) 逻辑分离的话,是不是会比较好呢?
  
  其实这个问题早就存在已久,从交互式网页开始风行时,不论是 ASP 或是 PHP 的使用者都是身兼程序开发者与视觉设计师两种身份。可是通常这些使用者不是程序强就是美工强,如果要两者同时兼顾,那可得死掉不少脑细胞...
  
  所以模版引擎就应运而生啦!模版引擎的目的,就是要达到上述提到的逻辑分离的功能。它能让程序开发者专注于资料的控制或是功能的达成;而视觉设计师则可专注于网页排版,让网页看起来更具有专业感!因此模版引擎很适合公司的网站开发团队使用,使每个人都能发挥其专长!
  
  就笔者接触过的模版引擎来说,依资料呈现方式大概分成:需搭配程序处理的模版引擎和完全由模版本身自行决定的模版引擎两种形式。
  
  在需搭配程序处理的模版引擎中,程序开发者必须要负责变量的呈现逻辑,也就是说他必须把变量的内容在输出到模版前先处理好,才能做 assign 的工作。换句话说,程序开发者还是得多写一些程序来决定变量呈现的风貌。而完全由模版本身自行决定的模版引擎,它允许变量直接 assign 到模版中,让视觉设计师在设计模版时再决定变量要如何呈现。因此它就可能会有另一套属于自己的模版程序语法 (如 Smarty) ,以方便控制变量的呈现。但这样一来,视觉设计师也得学习如何使用模版语言。
  
  模版引擎的运作原理,首先我们先看看以下的运行图:
   菜鸟学PHP之Smarty入门(组图)_PHP
  一般的模版引擎 (如 PHPLib) 都是在建立模版对象时取得要解析的模版,然后把变量套入后,透过 parse() 这个方法来解析模版,最后再将网页输出。
   菜鸟学PHP之Smarty入门(组图)_PHP
  对 Smarty 的使用者来说,程序里也不需要做任何 parse 的动作了,这些 Smarty 自动会帮我们做。而且已经编译过的网页,如果模版没有变动的话, Smarty 就自动跳过编译的动作,直接执行编译过的网页,以节省编译的时间。
  
  使用Smarty的一些概念
  
  在一般模版引擎中,我们常看到区域的观念,所谓区块大概都会长成这样:
  
  区域内容
  
  
  这些区块大部份都会在 PHP 程序中以 if 或 for, while 来控制它们的显示状态,虽然模版看起来简洁多了,但只要一换了显示方式不同的模版, PHP 程序势必要再改一次!
  
  在 Smarty 中,一切以变量为主,所有的呈现逻辑都让模版自行控制。因为 Smarty 会有自己的模版语言,所以不管是区块是否要显示还是要重复,都是用 Smarty 的模版语法 (if, foreach, section) 搭配变量内容作呈现。这样一来感觉上好象模版变得有点复杂,但好处是只要规划得当, PHP 程序一行都不必改。
  
  由上面的说明,我们可以知道使用Smarty 要掌握一个原则:将程序应用逻辑与网页呈现逻辑明确地分离。就是说 PHP 程序里不要有太多的 HTML 码。程序中只要决定好那些变量要塞到模版里,让模版自己决定该如何呈现这些变量 (甚至不出现也行) 。
  
  Smarty的基础
  
  安装Smarty

  
  首先,我们先决定程序放置的位置。
  
  Windows下可能会类似这样的位置:「 d:\appserv\web\demo\ 」。
  
  Linux下可能会类似这样的位置:「 /home/jaceju/public_html/ 」。
  
  到Smarty的官方网站下载最新的Smarty套件:http://smarty.php.net。
  
  解开 Smarty 2.6.0 后,会看到很多档案,其中有个 libs 资料夹。在 libs 中应该会有 3 个 class.php 檔 + 1 个 debug.tpl + 1 个 plugin 资料夹 + 1 个 core 资料夹。然后直接将 libs 复制到您的程序主资料夹下,再更名为 class 就可以了。就这样?没错!这种安装法比较简单,适合一般没有自己主机的使用者。
  
  至于 Smarty 官方手册中为什么要介绍一些比较复杂的安装方式呢?基本上依照官方的方式安装,可以只在主机安装一次,然后提供给该主机下所有设计者开发不同程序时直接引用,而不会重复安装太多的 Smarty 复本。而笔者所提供的方式则是适合要把程序带过来移过去的程序开发者使用,这样不用烦恼主机有没有安装 Smarty 。
  
  程序的资料夹设定
  
  以笔者在Windows安装Appserv为例,程序的主资料夹是「d:\appserv\web\demo\」。安装好Smarty后,我们在主资料夹下再建立这样的资料夹:
   菜鸟学PHP之Smarty入门(组图)_PHP
  在 Linux 底下,请记得将 templates_c 的权限变更为 777 。Windows 下则将其只读取消。
  
  第一个用Smarty写的小程序
  
  我们先设定 Smarty 的路径,请将以下这个档案命名为 main.php ,并放置到主资料夹下:
  
  main.php:
    include "class/Smarty.class.php";
  define('__SITE_ROOT', 'd:/appserv/web/demo'); // 最后没有斜线
  $tpl = new Smarty();
  $tpl->template_dir = __SITE_ROOT . "/templates/";
  $tpl->compile_dir = __SITE_ROOT . "/templates_c/";
  $tpl->config_dir = __SITE_ROOT . "/configs/";
  $tpl->cache_dir = __SITE_ROOT . "/cache/";
  $tpl->left_delimiter = '  $tpl->right_delimiter = '}>';
  ?>
  
  照上面方式设定的用意在于,程序如果要移植到其它地方,只要改 __SITE_ROOT 就可以啦。 (这里是参考 XOOPS 的 )
  
  Smarty 的模版路径设定好后,程序会依照这个路径来抓所有模版的相对位置 (范例中是 'd:/appserv/web/demo/templates/' ) 。然后我们用 display() 这个 Smarty 方法来显示我们的模版。
  
  接下来我们在 templates 资料夹下放置一个 test.htm:(扩展名叫什么都无所谓,但便于视觉设计师开发,笔者都还是以 .htm 为主。)
  
  templates/test.htm:
  
  
  
Statement of this Website
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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to make Google Maps the default map in iPhone How to make Google Maps the default map in iPhone Apr 17, 2024 pm 07:34 PM

The default map on the iPhone is Maps, Apple's proprietary geolocation provider. Although the map is getting better, it doesn't work well outside the United States. It has nothing to offer compared to Google Maps. In this article, we discuss the feasible steps to use Google Maps to become the default map on your iPhone. How to Make Google Maps the Default Map in iPhone Setting Google Maps as the default map app on your phone is easier than you think. Follow the steps below – Prerequisite steps – You must have Gmail installed on your phone. Step 1 – Open the AppStore. Step 2 – Search for “Gmail”. Step 3 – Click next to Gmail app

A Diffusion Model Tutorial Worth Your Time, from Purdue University A Diffusion Model Tutorial Worth Your Time, from Purdue University Apr 07, 2024 am 09:01 AM

Diffusion can not only imitate better, but also "create". The diffusion model (DiffusionModel) is an image generation model. Compared with the well-known algorithms such as GAN and VAE in the field of AI, the diffusion model takes a different approach. Its main idea is a process of first adding noise to the image and then gradually denoising it. How to denoise and restore the original image is the core part of the algorithm. The final algorithm is able to generate an image from a random noisy image. In recent years, the phenomenal growth of generative AI has enabled many exciting applications in text-to-image generation, video generation, and more. The basic principle behind these generative tools is the concept of diffusion, a special sampling mechanism that overcomes the limitations of previous methods.

Generate PPT with one click! Kimi: Let the 'PPT migrant workers' become popular first Generate PPT with one click! Kimi: Let the 'PPT migrant workers' become popular first Aug 01, 2024 pm 03:28 PM

Kimi: In just one sentence, in just ten seconds, a PPT will be ready. PPT is so annoying! To hold a meeting, you need to have a PPT; to write a weekly report, you need to have a PPT; to make an investment, you need to show a PPT; even when you accuse someone of cheating, you have to send a PPT. College is more like studying a PPT major. You watch PPT in class and do PPT after class. Perhaps, when Dennis Austin invented PPT 37 years ago, he did not expect that one day PPT would become so widespread. Talking about our hard experience of making PPT brings tears to our eyes. "It took three months to make a PPT of more than 20 pages, and I revised it dozens of times. I felt like vomiting when I saw the PPT." "At my peak, I did five PPTs a day, and even my breathing was PPT." If you have an impromptu meeting, you should do it

Clock app missing in iPhone: How to fix it Clock app missing in iPhone: How to fix it May 03, 2024 pm 09:19 PM

Is the clock app missing from your phone? The date and time will still appear on your iPhone's status bar. However, without the Clock app, you won’t be able to use world clock, stopwatch, alarm clock, and many other features. Therefore, fixing missing clock app should be at the top of your to-do list. These solutions can help you resolve this issue. Fix 1 – Place the Clock App If you mistakenly removed the Clock app from your home screen, you can put the Clock app back in its place. Step 1 – Unlock your iPhone and start swiping to the left until you reach the App Library page. Step 2 – Next, search for “clock” in the search box. Step 3 – When you see “Clock” below in the search results, press and hold it and

Can't allow access to camera and microphone in iPhone Can't allow access to camera and microphone in iPhone Apr 23, 2024 am 11:13 AM

Are you getting "Unable to allow access to camera and microphone" when trying to use the app? Typically, you grant camera and microphone permissions to specific people on a need-to-provide basis. However, if you deny permission, the camera and microphone will not work and will display this error message instead. Solving this problem is very basic and you can do it in a minute or two. Fix 1 – Provide Camera, Microphone Permissions You can provide the necessary camera and microphone permissions directly in settings. Step 1 – Go to the Settings tab. Step 2 – Open the Privacy & Security panel. Step 3 – Turn on the “Camera” permission there. Step 4 – Inside, you will find a list of apps that have requested permission for your phone’s camera. Step 5 – Open the “Camera” of the specified app

All CVPR 2024 awards announced! Nearly 10,000 people attended the conference offline, and a Chinese researcher from Google won the best paper award All CVPR 2024 awards announced! Nearly 10,000 people attended the conference offline, and a Chinese researcher from Google won the best paper award Jun 20, 2024 pm 05:43 PM

In the early morning of June 20th, Beijing time, CVPR2024, the top international computer vision conference held in Seattle, officially announced the best paper and other awards. This year, a total of 10 papers won awards, including 2 best papers and 2 best student papers. In addition, there were 2 best paper nominations and 4 best student paper nominations. The top conference in the field of computer vision (CV) is CVPR, which attracts a large number of research institutions and universities every year. According to statistics, a total of 11,532 papers were submitted this year, and 2,719 were accepted, with an acceptance rate of 23.6%. According to Georgia Institute of Technology’s statistical analysis of CVPR2024 data, from the perspective of research topics, the largest number of papers is image and video synthesis and generation (Imageandvideosyn

From bare metal to a large model with 70 billion parameters, here is a tutorial and ready-to-use scripts From bare metal to a large model with 70 billion parameters, here is a tutorial and ready-to-use scripts Jul 24, 2024 pm 08:13 PM

We know that LLM is trained on large-scale computer clusters using massive data. This site has introduced many methods and technologies used to assist and improve the LLM training process. Today, what we want to share is an article that goes deep into the underlying technology and introduces how to turn a bunch of "bare metals" without even an operating system into a computer cluster for training LLM. This article comes from Imbue, an AI startup that strives to achieve general intelligence by understanding how machines think. Of course, turning a bunch of "bare metal" without an operating system into a computer cluster for training LLM is not an easy process, full of exploration and trial and error, but Imbue finally successfully trained an LLM with 70 billion parameters. and in the process accumulate

A must-read for technical beginners: Analysis of the difficulty levels of C language and Python A must-read for technical beginners: Analysis of the difficulty levels of C language and Python Mar 22, 2024 am 10:21 AM

Title: A must-read for technical beginners: Difficulty analysis of C language and Python, requiring specific code examples In today's digital age, programming technology has become an increasingly important ability. Whether you want to work in fields such as software development, data analysis, artificial intelligence, or just learn programming out of interest, choosing a suitable programming language is the first step. Among many programming languages, C language and Python are two widely used programming languages, each with its own characteristics. This article will analyze the difficulty levels of C language and Python

See all articles