search
HomeBackend DevelopmentPHP Tutorial教你如何用PHP制作静态网站的模板框架_PHP

第一个目的是谈论得最多的目的,它设想的情形是:一组程序员编写用于生成页面内容的PHP脚本,同时另一组设计人员设计HTML和图形以控制页面的最终外观。分离功能和布局的基本思想就是使得这两组人能够各自编写和使用独立的一组文件:程序员只需关心那些只包含PHP代码的文件,无需关心页面的外观;而页面设计人员可以用自己最熟悉的可视化编辑器设计页面布局,无需担心破坏任何嵌入到页面的PHP代码。

  如果你曾经看过几个关于PHP模板的教程,那么你应该已经明白模板的工作机制。考虑一个简单的页面局部:页面的上方是页头,左边是导航条,其余部分是内容区域。

  可以看出页面如何由模板构造而成:main模板控制着整个页面的布局;header模板和leftnav模板控制着页面的公共元素。花括号“{}”里面的标识符是内容占位符。使用模板最主要的好处在于界面设计者能够按照自己的意愿编辑这些文件,比如设置字体、修改颜色和图形,或者完全地改变页面的布局。界面设计者可以用任何普通HTML编辑器或者可视化工具编辑这些页面,因为这些文件都只包含HTML代码,没有任何PHP代码。

  PHP代码全部保存到单独的文件中,这个文件也就是由页面URL实际调用的文件。Web服务器通过PHP引擎解析该文件,然后把结果返回给浏览器。一般地,PHP代码总是动态地生成页面内容,比如查询数据库或者执行某种计算等。下面是一个例子:

// 此处的PHP代码设置$content

使其包含合适的页面内容



$tpl->assign('CONTENT', $content); 



$tpl->parse('HEADER', 'header'); 



$tpl->parse('LEFTNAV', 'leftnav'); 



$tpl->parse('MAIN', 'main'); 



$tpl->FastPrint('MAIN'); 



?>

  这里我们使用的是流行的FastTemplate模板类,但其基本思路对于其他许多模板类来说都一样。首先你实例化一个类,告诉它到哪里去寻找模板文件以及哪一个模板文件与页面的哪部分对应;接下来是生成页面内容,把结果赋予内容的标识符;然后,依次解析各个模板文件,模板类将执行必要的替换操作;最后把解析结果输出到浏览器。

  这个文件完全由PHP代码构成,不包含任何HTML代码,这是它最大的优点。现在,PHP程序员可以集中精力编写生成页面内容的代码,而不必为了如何生成HTML去正确地格式化最终页面而担心。

  很容易看出采用模板还有第二个好处。如上例所示,页面左边的导航条单独保存为一个文件,我们只需编辑这一个模板文件就可以改变网站所有页面左边的导航条。

  避免页面元素重复

  “这确实不错”,你也许会想,“我的网站主要就是由大量的静态页面构成。现在我可以从所有页面中删除它们的公共部分,要更新这些公共部分实在太麻烦了。以后我就可以用模板制作出很容易维护的统一页面布局。”但事情并非这么简单,“大量的静态页面”道出了问题的所在。

  请考虑上面的例子。这个例子实际上只有一个example.php页面,它之所以能够生成整个网站的所有页面,是因为它利用了URL中的查询字符串从数据库之类的信息源动态地构造出页面。

  我们之中的大多数人所运行的网站并不一定都有数据库支持。我们的网站大多数由静态页面构成,然后用PHP在这里、那里加上一些动态功能,比如搜索引擎、反馈表单等。那么,如何在这种网站上应用模板呢?

  最简单的方法是为每一个页面复制一份PHP文件,然后在每一个页面中把PHP代码里代表内容的变量设置成合适的页面内容。例如,假设有三个页面,它们分别是主页(home)、关于(about)和产品(product),我们可以用三个文件分别生成它们。这三个文件的内容都类如:

<p>希望你能够喜欢本网站</p>"; 



$tpl->assign('CONTENT', $content); 



$tpl->parse('HEADER', 'header'); 



$tpl->parse('LEFTNAV', 'leftnav'); 



$tpl->parse('MAIN', 'main'); 



$tpl->FastPrint('MAIN'); 



?>

  显然,这种方法有三个问题:我们必须为每一个页面复制这些复杂的、牵涉到模板的PHP代码,这与重复公共页面元素一样使得页面难以维护;现在文件又混合了HTML和PHP代码;为内容变量赋值将变得非常困难,因为我们必须处理好大量的特殊字符。

  解决这个问题的关键就在于分离PHP代码和HTML内容,虽然我们不能从文件中删除所有的HTML内容,但可以移出绝大多数PHP代码。

  静态网站的模板框架:

ob_end_clean(); 



$tpl->assign('CONTENT', $content); 



$tpl->parse('HEADER', 'header'); 



$tpl->parse('LEFTNAV', 'leftnav'); 



$tpl->parse('MAIN', 'main'); 



$tpl->FastPrint('MAIN'); 



} 



?>

  ageStart函数首先创建并设置了一个模板实例,然后启用输出缓存。此后,所有来自页面本身的HTML内容都将进入缓存。pageFinish函数取出缓存中的内容,然后在模板对象中指定这些内容,最后解析模板并输出完成后的页面。

  这就是整个模板框架全部的工作过程了。首先编写包含了网站各个页面公共元素的模板,然后从所有页面中删除全部公共的页面布局代码,代之以三行永远无需改动的PHP代码;再把FastTemplate类文件和prepend.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
PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

How does PHP handle object cloning (clone keyword) and the __clone magic method?How does PHP handle object cloning (clone keyword) and the __clone magic method?Apr 17, 2025 am 12:24 AM

In PHP, use the clone keyword to create a copy of the object and customize the cloning behavior through the \_\_clone magic method. 1. Use the clone keyword to make a shallow copy, cloning the object's properties but not the object's properties. 2. The \_\_clone method can deeply copy nested objects to avoid shallow copying problems. 3. Pay attention to avoid circular references and performance problems in cloning, and optimize cloning operations to improve efficiency.

PHP vs. Python: Use Cases and ApplicationsPHP vs. Python: Use Cases and ApplicationsApr 17, 2025 am 12:23 AM

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.

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

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)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool