PHPマニュアル/PEARマニュアル | ユーザフォーラムで議論/質問 | マニュアル検索 | ハイライト | ハイライトオフ | ポータル | php spot

Componentized Templates | JavaScript入門&応用&リファレンスなら「JavaScriptist」

  

Componentized Templates

This tip is a bit of a hack, but still a neat idea. Use at your own risk. ;-)

Traditionally, programming templates into your applications goes as follows: First, you accumulate your variables within your PHP application, (maybe with database queries.) Then, you instantiate your Smarty object, assign the variables and display the template. So lets say for example we have a stock ticker on our template. We would collect the stock data in our application, then assign these variables in the template and display it. Now wouldn't it be nice if you could add this stock ticker to any application by merely including the template, and not worry about fetching the data up front?

You can embed PHP into your templates with the {php}{/php} tags. With this, you can setup self contained templates with their own data structures for assigning their own variables. With the logic embedded like this, you can keep the template & logic together. This way no matter where the template source is coming from, it is always together as one component.

Example 18-7. componentized template

{* Smarty *}

{php}

	// setup our function for fetching stock data
	function fetch_ticker($symbol,&$ticker_name,&$ticker_price) {
		// put logic here that fetches $ticker_name
		// and $ticker_price from some resource
	}

	// call the function
	fetch_ticker("YHOO",$ticker_name,$ticker_price);
	
	// assign template variables
    $this->assign("ticker_name",$ticker_name);
    $this->assign("ticker_price",$ticker_price);

{/php}

Stock Name: {$ticker_name} Stock Price: {$ticker_price}

As of Smarty 1.5.0, there is even a cleaner way. You can include php in your templates with the {include_php ...} tag. This way you can keep your PHP logic separated from the template logic. See the include_php function for more information.

Example 18-8. componentized template with include_php

load_ticker.php
---------------

<?php
	// setup our function for fetching stock data
	function fetch_ticker($symbol,&$ticker_name,&$ticker_price) {
		// put logic here that fetches $ticker_name
		// and $ticker_price from some resource
	}

	// call the function
	fetch_ticker("YHOO",$ticker_name,$ticker_price);
	
	// assign template variables
    $this->assign("ticker_name",$ticker_name);
    $this->assign("ticker_price",$ticker_price);
?>


index.tpl
---------

{* Smarty *}

{include_php file="load_ticker.php"}

Stock Name: {$ticker_name} Stock Price: {$ticker_price}
忘却曲線を使ってこの知識を確実に記憶に残す

フォーラムで「Componentized Templates」について話す
各種マニュアル: PHPマニュアル | PEARマニュアル | Smarty(英語)マニュアル | PHP-GTKマニュアル | Componentized Templates」をGoogle検索
copyright © 1997-2024 PHP ドキュメント作成グループ(ライセンス). provided by php spot. マニュアル: