Get Smarty

Donate

Smarty Icon

You may use the Smarty logo according to the trademark notice.

Smarty Template Engine Smarty Template Engine

For sponsorship, advertising, news or other inquiries, contact us at:

Sites Using Smarty

Buy cheap glasses from Cheapglasses123.com and save up to 80%.

Where to buy prescription glasses? EyewearCanada.com is your best choice!

Visit www.sport-kick.com for cheap soccer cleats, sneakers and Soccer Jerseys updates

Advertisement

组件化模板

传统来说,应用程序使用模板编程都按这样的方式: 先在PHP程序中,将需要的变量都获取到 (可能还会通过数据库获取), 然后实例化Smarty对象,调用assign()来赋值变量,并且display()。 好的,我们来看看模板上显示股票的例子吧。 我们会在程序中收集到股票的数据,然后将数据变量赋值到模板,并且显示模板。 现在,如果你可以在模板简单地获取到任意来源的股票数据,不需要担心在前端获取这些数据,不是更好吗?

你可以编写一个自定义扩展,来获取内容并且赋值到模板的变量。

Example 21.7. 组件化模板

function.load_ticker.php - 文件在 $plugins 目录


<?php

// setup our function for fetching stock data
function fetch_ticker($symbol)
{
   // put logic here that fetches $ticker_info
   // from some ticker resource
   return $ticker_info;
}

function smarty_function_load_ticker($params, $smarty)
{
   // call the function
   $ticker_info = fetch_ticker($params['symbol']);

   // assign template variable
   $smarty->assign($params['assign'], $ticker_info);
}
?>

    

index.tpl


{load_ticker symbol='SMARTY' assign='ticker'}

Stock Name: {$ticker.name} Stock Price: {$ticker.price}

    

参见 {include_php}, {include}{php}.

Comments
No comments for this page.

Advertisement