Smarty是一个PHP下的网页模板系统。Smarty基本上是一种为了将不同考量的事情分离而推出的工具,这对某些应用程序是一种共通性设计策略。[2][3]

Quick Facts 开发者, 当前版本 ...
Smarty Templates
Thumb
开发者Monte Ohrt, Messju Mohr
当前版本3.1.27(2015年6月19日,​9年前​(2015-06-19[1]
源代码库 编辑维基数据链接
类型网页模板引擎
许可协议LGPL
网站smarty.net
Close

简介

Smarty以在文件中放置特殊的“Smarty标签”来产生网页内容。这些标签会被处理并替换成其他的内容。

标签是给Smarty的指令符,以模板定界符包住。这些指令符可以是变数,以$符号代表函数、逻辑流程控制语法。Smarty允许PHP程序员以Smarty标签去定义可存取的函数。

Smarty意图简化区域化,允许PHP网页后端逻辑与表现层(即使用者界面)分离。理想的情况下,这将降低软件维护费用和人力。在这个研发策略之下,设计师可专注于实现表现层而不用撰写PHP程式码,并允许PHP程序员抽离出表现层并专注实现后端逻辑。

Smarty支援几个高阶模板程式的特性,包含:

  • 正规表示法
  • 流程控制语法,如foreach、while。
  • if,elseif,else
  • 可修改的变数 - 例如{$variable|nl2br}
  • 使用者自订的函数
  • 在模板内的数学计算

以及其他特性。一些其他的模板引擎也支援这类特性。

程式码范例

因为 Smarty将 HTML码与PHP程式码分离,所以会有两个档案:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html>
<head>
   <title>{$title_text}</title>
   <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
</head>

<body> {* This is a little comment that won't be visible in the HTML source *}

<p>{$body_text}</p>

</body><!-- this is a little comment that will be seen in the HTML source -->
</html>

在企业逻辑程式码中,设计者能配置Smarty去使用这个模板:

define('SMARTY_DIR', 'smarty-2.6.9/' );
require_once(SMARTY_DIR . 'Smarty.class.php');

$smarty = new Smarty();
$smarty->template_dir = './templates/';
$smarty->compile_dir = './templates/compile/';
$smarty->cache_dir = './templates/cache/';
$smarty->caching = false;
$smarty->error_reporting = E_ALL; // LEAVE E_ALL DURING DEVELOPMENT
$smarty->debugging = true;

$smarty->assign('title_text', 'TITLE: This is the Smarty basic example ...');
$smarty->assign('body_text', 'BODY: This is the message set using assign()');

$smarty->display('index.tpl');

并且能将PHP包涵在Smarty模板里,像是下面这样:

{* We can use PHP syntax in smarty template inside {php} ..{/php} *}
{php} 
$contentType = strpos($_SERVER['HTTP_ACCEPT']'application/xhtml+xml') === false ? 'text/html' : 'application/xhtml+xml';
header("Content-Type: $contentType; charset=utf-8"); 
{/php}
<html>
<head>
<title>{$page_title}</title>
</head>
<body>
   {$body_text}
</body>
</html>

参照

参见

外部链接

Wikiwand in your browser!

Seamless Wikipedia browsing. On steroids.

Every time you click a link to Wikipedia, Wiktionary or Wikiquote in your browser's search results, it will show the modern Wikiwand interface.

Wikiwand extension is a five stars, simple, with minimum permission required to keep your browsing private, safe and transparent.