跳至内容

{$smarty} 保留变量

可以用来访问几个环境和请求变量的 PHP 保留变量 {$smarty} 。以下给出了完整的列表。

请求变量

请求变量 例如 $_GET$_POST$_COOKIE$_SERVER$_ENV$_SESSION 可以访问,如下例所示

{* display value of page from URL ($_GET) http://www.example.com/index.php?page=foo *}
{$smarty.get.page}

{* display the variable "page" from a form ($_POST['page']) *}
{$smarty.post.page}

{* display the value of the cookie "username" ($_COOKIE['username']) *}
{$smarty.cookies.username}

{* display the server variable "SERVER_NAME" ($_SERVER['SERVER_NAME'])*}
{$smarty.server.SERVER_NAME}

{* display the system environment variable "PATH" *}
{$smarty.env.PATH}

{* display the php session variable "id" ($_SESSION['id']) *}
{$smarty.session.id}

{* display the variable "username" from merged get/post/cookies/server/env *}
{$smarty.request.username}

注意

由于历史原因,{$SCRIPT_NAME}{$smarty.server.SCRIPT_NAME} 的简写。

<a href="{$SCRIPT_NAME}?page=smarty">click me</a>
<a href="{$smarty.server.SCRIPT_NAME}?page=smarty">click me</a>

注意

尽管 Smarty 为了方便提供了对 PHP 超级全局的直接访问,但应谨慎使用。直接访问超级全局会混合底层应用程序代码结构和模板。一个好做法是将具体的所需值分配给模板变量。

{$smarty.now}

可以使用 {$smarty.now} 访问当前的 时间戳。该值反映了自 1970 年 1 月 1 日的所谓的 Epoch 以来经过的秒数,并可以直接传递给 date_format 修饰符以显示。请注意,每次调用时都会调用 time();例如,使用 $smarty.now 在开始和结束时调用一个需要三秒执行的脚本将显示三秒的差异。

{* use the date_format modifier to show current date and time *}
{$smarty.now|date_format:'%Y-%m-%d %H:%M:%S'}

{$smarty.const}

可以直接访问 PHP 常量值。

<?php
// the constant defined in php
define('MY_CONST_VAL','CHERRIES');

使用以下模板输出常量:

{$smarty.const.MY_CONST_VAL}

注意

尽管 Smarty 为了方便提供了对 PHP 常量的直接访问,但通常会避免这样做,因为这样做会将底层应用程序代码结构混入模板中。一个好做法是将特定所需值分配给模板变量。

{$smarty.capture}

可以通过内置 {capture}..{/capture} 函数捕获的模板输出,可通过 {$smarty.capture} 变量进行访问。请参阅 {capture} 页面了解更多信息。

{$smarty.config}

{$smarty.config} 变量可用于引用已加载的 配置变量{$smarty.config.foo}{#foo#} 的同义词。请参阅 {config_load} 页面了解更多信息。

{$smarty.section}

{$smarty.section} 变量可用于引用 {section} 循环属性。这些属性具有非常有用的值,例如 .first.index 等。

注意

{$smarty.foreach} 变量在新 {foreach} 语法中不再使用,但在 Smarty 2.x 风格的 foreach 语法中仍然受支持。

{$smarty.template}

返回正在处理的当前模板的名称(不含目录)。

{$smarty.template_object}

返回正在处理的当前模板的模板对象。

{$smarty.current_dir}

如果从文件系统(默认)加载正在处理的当前模板,则返回其目录的名称。

{$smarty.version}

返回模板编译所使用的 Smarty 版本。

<div id="footer">Powered by Smarty {$smarty.version}</div>

{$smarty.block.child}

返回子模板的块文本。请参阅 模板继承

{$smarty.block.parent}

返回父模板的块文本。请参阅 模板继承

{$smarty.ldelim}, {$smarty.rdelim}

这些变量用于逐字节打印左定界符和右定界符的值,与 {ldelim},{rdelim} 相同。

另请参阅 已分配变量配置变量