hitoshop14 @ ウィキ

基本動作

最終更新:

hitoshop

- view
管理者のみ編集可

基本動作

ここでは、基本となるSmartyの動作を確認しましょう。Smartyがインストールされていることを前提にして説明します。
とりあえず、testSmartyフォルダを作成して、その中にテンプレートファルダ(templates, templates_c)や、phpファイルなどを配置して、実行します。
注意 本番環境では、公開ディレクトリ内にテンプレートフォルダ(templates, templates_c)を配置することは避けるべきです。なぜかというと、直接URLを記述されて、テンプレートファイル自体を覗くことができるのでセキュリティーの観点からやめるべきです。

◆Windows環境(Xanpp)
    C:\xampp\htdocs\testSmarty
    C:\xampp\htdocs\testSmarty\templates
    C:\xampp\htdocs\testSmarty\templates_c

◆Linux環境
    /var/www/html/testSmarty
    /var/www/html/templates
    /var/www/html/templates_c

templatesフォルダ内に( tplファイル、htmlファイル )を置きます。
templates_cフォルダ内には、ユーザが直接何かをするわけではなく、一度phpファイルを実行することにより、コンパイルされたファイルが自動的に格納され、2回目以降の処理を早くします。

HelloSmarty.php

<?php
require_once 'Smarty.class.php';
$smt = new Smarty();                                   //Smartyクラスのインスタンス化
$smt->templates_dir = './tempaltes/';         //Smarytオブジェクトを設定
$smt->compile_dir = './templates_c/';        //Smarytオブジェクトを設定
$smt->assign('name', 'こんにちわ');          //テンプレート変数の設定
$smt->display('viewHello.tpl');                     //テンプレートの呼び出し

 

viewHello.tpl

<html>
<head><title>Smartyの基本</title></head>
<body>
    <h1>Helloとは、{$name}です。</h1>
</body>
</html>

 

 

 

 

テンプレートの構造

サンプル.tpl

<html>
<head><title>Smartyの構造</title></head>
<body>
    <table border='1'>
    <tr>
           <th>名前</th><th>住所</th><th>電話番号</th><th>メール</th>
    </tr>
    {* foreach関数のサンプル *}
    {foreach from = $data item = 'value'}
    <tr>
           <td>{$value.name | escape}</td>
           <td>{$value.address | escape}</td>
           <td>{$value.tel}</td>
           <td>{$value.mail | escape}</td>
    </tr>
    {/foreach}
    </table>
</body>
</html>

 

 



 

 

 

記事メニュー
人気記事ランキング
目安箱バナー