Smartyの使い方

概要

PHP のテンプレートエンジンSmartyの使い方を調べてみました。
Smartyを使うと『画面表示のためのデザイン部分』と『アプリケーションのプログラム部分』を分けて開発することが容易になります。

目次

ファイル構成

Smartyを使うには、デザイン部分に「templates」「templates_c」「configs」「cache」の4つのフォルダを作成します。
これらはSmartyのプログラム部分から呼び出されるファイルになるため、webサーバーの公開領域に設置する必要はありません。
PHPの届く範囲にあれば大丈夫です。

webブラウザから直接アクセスされるのはSmartyのプログラム部分となります。

var/www/
    ┣ html
    ┃  ┗ smarty_sample
    ┃
    ┗ private
        ┗ smarty_sample_tpl
            ┣ cache (書き込み権限)
            ┣ configs
            ┣ templates
            ┗ templates_c (書き込み権限)

Smartyは「cache」と「templates_c」にファイルを書き込むため、webサーバーのユーザー権限での書き込み許可が必要です。

簡単なサンプルプログラム

それでは簡単なサンプルプログラムを作成して実際の動きを見てみます。
ファイル構成は上記を参照して作成します。

  1. まずは、表示部分のテンプレートファイルを作成します。
    {* var/www/private/smarty_sample_tpl/templates/index.tpl *}
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="ja" lang="ja">
    <head>
    <meta http-equiv="Content-Type" content="text/html;charset=Shift_JIS" />
    <title>Smartyのサンプルプログラム</title>
    </head>
    <body>
    
    こんにちは、{$name|escape}さん。ようこそ Smarty の世界へ!
    
    </body>
    </html>
    

    {* *}で囲まれた部分は .tpl ファイルのコメントです。

  2. 次に、webブラウザから直接アクセスされる Smarty のプログラム部分を作成します。

    Smarty のインスタンスを作成し、テンプレート変数を絶対パスで割り当てます。
    そして「assign」メソッドを使ってテンプレートファイルに記述された変数に渡す値を設定します。
    今回は「name」変数に「dugong」と設定しています。

    最後に「display」メソッドを使ってテンプレートファイルを呼び出し、画面表示を行っています。

    <?php
    // var/www/html/smarty_sample/index.php
    
    require_once('Smarty.class.php');
    $smarty = new Smarty();
    
    $smarty->template_dir = 'var/www/private/smarty_sample_tpl/templates/';
    $smarty->compile_dir  = 'var/www/private/smarty_sample_tpl/templates_c/';
    $smarty->config_dir   = 'var/www/private/smarty_sample_tpl/configs/';
    $smarty->cache_dir    = 'var/www/private/smarty_sample_tpl/cache/';
    
    $smarty->assign('name','dugong');
    
    $smarty->display('index.tpl');
    
    ?>
    

    レンタルサーバーの場合、ftpでSmartyのlibsフォルダをサーバーにアップして、
    require_once(SMARTY_DIR . ' var/www/html/smarty/libs/Smarty.class.php');
    と絶対パスで指定すればOK!

  3. 実行結果

    実行結果

投稿日:

ページのトップへ戻る