Smarty

维基百科,自由的百科全书
跳转到导航 跳转到搜索
Smarty Templates
File:Smarty-logo.gif
开发者Monte Ohrt, Messju Mohr
当前版本3.1.27(2015年6月19日,​11年前​(2015-06-19[1]
源代码库
  • {{URL|example.com|可选的显示文本}}
Module:EditAtWikidata第29行Lua错误:attempt to index field 'wikibase' (a nil value)
引擎
    Module:EditAtWikidata第29行Lua错误:attempt to index field 'wikibase' (a nil value)
    类型网页模板引擎
    许可协议LGPL
    网站smarty.net

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

    简介[编辑]

    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>
    

    参照[编辑]

    1. ^ 存档副本. [2015-08-07]. (原始内容存档于2019-02-17). 
    2. ^ Smarty将PHP码(事务逻辑英语Business logic)与 HTML码分开(通常代表表现逻辑英语Presentation logic).
    3. ^ Parr, Terence John. Enforcing strict model-view separation in template engines. Proceedings of the 13th international conference on World Wide Web. 2004. 1-58113-844-X. 

    参见[编辑]

    外部链接[编辑]

    英文[编辑]

    中文[编辑]