search
HomeBackend DevelopmentPHP TutorialPHP模板引擎Smarty内建函数详解_php实例

PHP模板引擎Smarty内建函数详解_php实例

Jun 07, 2016 pm 05:08 PM
phpsmartybuilt-in functionstemplate engine

本文实例讲述了PHP模板引擎Smarty内建函数。分享给大家供大家参考,具体如下:

Smarty 的内建函数:Smarty自带一些内建函数,内建函数是模板语言的一部分,用户不能创建名称和内建函数一样的自定义函数,也不能修改内建函数。

下面对 Smarty 中的内建函数进行说明,并加以实例:

实例中使用到的 Smarty 模板引擎初始化文件 init.inc.php 和主文件 index.php

init.inc.php

<&#63;php
  define('ROOT_PATH', dirname(__FILE__)); //设置网站根目录
  require ROOT_PATH.'/libs/Smarty.class.php'; //加载 Smarty 模板引擎
  $_tpl = new Smarty(); //创建一个实例对象
  $_tpl->template_dir = ROOT_PATH.'/tpl/'; //重新指定模板目录
  $_tpl->compile_dir = ROOT_PATH.'./com/'; //重新指定编译目录
  $_tpl->left_delimiter = '<{'; //重新指定左定界符
  $_tpl->right_delimiter = '}>'; //重新指定右定界符
&#63;>

index.php

<&#63;php
  require 'init.inc.php'; //引入模板初始化文件
  global $_tpl;
  $_tpl->display('index.tpl'); //引入模板
&#63;>

1、capture

属性 类型 是否必须 缺省值 描述
name string no default 数据采集区域名称
assign string No n/a 数据采集区域在哪分配给变量name[待考]

/tpl/index.tpl

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Capture</title>
</head>
<body>
   <!-- 定义capture -->
   <{capture name="foo"}>
     这里是 capture 函数里面的内容,默认是不显示的。
   <{/capture}>
   <!-- 调用capture,使用的是 Smarty 中的保留变量{$smarty.capture} -->
   <{$smarty.capture.foo}>
</body>
</html>

2、config_load

属性 类型 是否必须 缺省值 描述
file string Yes n/a 待包含的配置文件的名称
section string No n/a 配置文件中待加载部分的名称
scope string no local 加载数据的作用域,取值必须为local, parent 或 global. local 说明该变量的作用域为当前模板. parent 说明该变量的作用域为当前模板和当前模板的父模板(调用当前模板的模板). global 说明该变量的作用域为所有模板.
global boolean No No 说明加载的变量是否全局可见,等同于 scope=parent. 注意: 当指定了 scope 属性时,可以设置该属性,但模板忽略该属性值而以 scope 属性为准。
config_load 函数用于从配置文件中加载变量,关于 config_load 函数的使用,可参考前面一篇《PHP模板引擎Smarty之配置文件在模板变量中的使用方法示例》。

3、include

属性 类型 是否必须 缺省值 描述
file string Yes n/a 待包含的模板文件名
assign string No n/a 该属性指定一个变量保存待包含模板的输出
[var ...] [var type] No n/a 传递给待包含模板的本地参数,只在待包含模板中有效

include 函数用于在当前模板中包含其它模板, 当前模板中的变量在被包含的模板中可用. 必须指定 file 属性,该属性指明模板资源的位置。如果设置了 assign 属性,该属性对应的变量名用于保存待包含模板的输出,这样待包含模板的输出就不会直接显示了。请看下面的示例:

/tpl/index.tpl

{include file="header.tpl"}
{* body of template goes here *}
{include file="footer.tpl"}

4、if,elseif,else

Smarty 中的 if 语句和 php 中的 if 语句一样灵活易用,并增加了几个特性以适宜模板引擎. if 必须于 /if 成对出现. 可以使用 else 和 elseif 子句。

可以使用以下条件修饰词:eq、ne、neq、gt、lt、lte、le、gte、ge、is even、is odd、is not even、is not odd、not、mod、div by、even by、odd by、==、!=、>、=. 使用这些修饰词时必须和变量或常量用空格格开。

下面对这些修饰符表示的意思进行说明:

条件修饰符 作用描述
eq ==
ne !=
neq !=
gt >
lt
lte
le
gte >=
ge >=
is even 是否偶数
is odd 是否奇数
is not even 是否不是偶数
is not odd    是否不是奇数
not !=
mod 求模
div by 是否能被整除
even by 商是否是偶数
odd by 商是否是奇数
&&
||
() 括号改变优先级

5、ldelim 和 rdelim

用于输出分隔符,也就是大括号 "{" 和 "}". 模板引擎总是尝试解释大括号内的内容,因此如果需要输出大括号,请使用此方法。请看下面的示例:

/tpl/index.tpl

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>ldelim 和 rdelim</title>
</head>
<body>
  <{ldelim}>funcname<{rdelim}> 是 Smarty 中的一个函数。
  <!-- 执行结果: <{funcname}> 是 Smarty 中的一个函数。 -->
</body>
</html>

6、literal

literal 标签区域内的数据将被当作文本处理,此时模板将忽略其内部的所有字符信息. 该特性用于显示有可能包含大括号等字符信息的 javascript 脚本. 当这些信息处于 {literal}{/literal} 标签中时,模板引擎将不分析它们,而直接显示,其实按照我的所有例子中的标签风格(因为在 init.inc.php 初始化文件中已经重新设置了左定界符和右定界符),而不是 Smarty 的默认风格,基本上不会产生这种情况。关于该函数的使用,请看下面的示例

/tpl/index.tpl

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>literal</title>
</head>
<body>
  <{literal}>
  <script language=javascript>
     <!--
       window.alert(new Date());
     -->
  </script>
  <{/literal}>
</body>
</html>

7、php

php 标签允许在模板中直接嵌入 php 脚本,此标签会把标签内部的内容当成 PHP 脚本进行解析执行。请看下面的示例

/tpl/index.tpl

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>php</title>
</head>
<body>
  <{php}>
    echo date("Y-m-d H:i:s");
  <{/php}>
  <!-- 执行结果: 2011-10-24 04:35:03 -->
</body>
</html>

8、strip

Web 开发者多次遇到空格和回车影响HTML输出的情形,为了得到特定的结果,因此你不得不在模板里运行所有的标签. 通常在难以理解或难以处理的模板中遇到此问题。Smarty 在显示前将除区任何位于 {strip}{/strip} 标记中数据的首尾空格和回车. 这样可以保证模板容易理解且不用担心多余的空格导致问题。

好了, Smarty 模板引擎中的内建函数先总结这么多,关于内建函数中两个最重要的函数(foreach,foreachelse、section,sectionelse)的使用,可参考前面一篇《PHP模板引擎Smarty内建函数foreach,foreachelse用法分析》

更多关于PHP相关内容感兴趣的读者可查看本站专题:《smarty模板入门基础教程》、《PHP模板技术总结》、《PHP基于pdo操作数据库技巧总结》、《PHP运算与运算符用法总结》、《PHP网络编程技巧总结》、《PHP基本语法入门教程》、《php面向对象程序设计入门教程》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》

希望本文所述对大家基于smarty模板的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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

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.

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

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools