Welcome to Programmer's Room   

PHP-Smartyの使い方

Smartyの使い方

インストール

1.ファイルのダウンロード

	http://www.smarty.net/からSmartyをダウンロードします。
	2008-09-07現在のバージョンは2.6.20です。

2.ファイルの解凍

	ダウンロードしたファイルを解凍したら"libs"というフォルダを使用します。
	どこにおいても大丈夫ですが、httpでアクセスできない場所がセキュリティのためにも良いと
	書かれています。レンタルのウェブスペースに設置するときはそうもいかないでしょうから、
	普通に"libs"フォルダをそのまま全部FTPなどでアップロードするしかないですね。

3.フォルダの作成

	やはりどこでも良いのですが、次のフォルダを作成します。
		templates
		templates_c
		cache
		configs
	templates_cとcacheは書き込み可にしておきます。
	
4.Smartyの読み込みとフォルダの指定

	次のスクリプトを適当な名前をつけてウェブで読める位置に設置します。
	私はsetup.phpという名前にしてルーとフォルダにおきました。
	それぞれのパスは実際のファイルとフォルダに通るようにします。
	レンタルのウェブスペースを使っているときは相対パスで指定します。

	<?php
	require('D:/php-5.2.5/libs/Smarty.class.php');
	$smarty = new Smarty();
	$smarty->template_dir = 'd:/smarty/templates';
	$smarty->compile_dir = 'd:/smarty/templates_c';
	$smarty->cache_dir = 'd:/smarty/cache';
	$smarty->config_dir = 'd:/smarty/configs';
	?>

5.テンプレートの作成
	
	次のテンプレートを作成して前のtemplatesフォルダにおきます。
	これはダウンロードしたSmartyの中にあるサンプルです。
	{$name}のところにphpスクリプトで指定した名前が入ります。
	日本語でも普通に使えます。
	私はルートフォルダにtest.tplという名前にして置きました。

	<html>
	<head>
	<title>Smarty</title>
	</head>
	<body>
	Hello!!!!, {$name}!
	</body>
	</html>
	
6.phpスクリプトの作成

	次のスクリプトをtest.phpという名前でルートフォルダに置きました。

	<?php
	include "setup.php";
	$smarty->assign('name', '括@〜−');
	$smarty->display('test.tpl');
	?>

	
これで必要なことはすべて完了しました。
作成したスクリプトをブラウザで呼び出してみてください。

	Hello!!!!, 括@〜−!
	
という一行が表示されるはずです。
特殊文字でも文字化けしていないですね。


7.配列の出力

	テンプレート(test2.tpl)
	
	<html>
	<head>
	<title>Smarty</title>
	</head>
	<body>
	<ul>
	{foreach from=$myArray key=k item=v}
	   <li>{$k}: {$v}</li>
	{/foreach}
	</ul>
	</body>
	</html>
	
	phpスクリプト(test2.php)
	
	<?php
	include "setup.php";
	$arr = array(9 => 'Tennis', 3 => 'Swimming', 8 => 'Coding');
	$smarty->assign('myArray', $arr);
	$smarty->display('test2.tpl');
	?>


	テンプレート(test3.tpl)

	<html>
	<head>
	<title>Smarty</title>
	</head>
	<body>
	<ul>
	{foreach from=$items key=myId item=i}
	  <li><a href="item.php?id={$myId}">{$i.no}: {$i.label}</li>
	{/foreach}
	</ul>
	</body>
	</html>
	
	phpスクリプト(test3.php)
	
	<?php
	include "setup.php";
	
	$items_list = array(23 => array('no' => 2456, 'label' => 'Salad'),
						96 => array('no' => 4889, 'label' => 'Cream')
						);
	$smarty->assign('items', $items_list);
	$smarty->display('test3.tpl');
	?>
	
【 戻 る 】