Archive for 2月 20th, 2012

  1. Hello, Smarty World!

    Posted on 2月 20th, 2012 by cx20

    Smarty

    Smarty は PHP 用のテンプレートエンジンである。名前の由来は「スマート(smart)」から。
    ページにアクセスするとテンプレートはコンパイルされ PHP スクリプトに展開される。

    ソースコード(テンプレート)

    <html>
      <head>
         <title>Hello, World!</title>
      </head>
      <body>
        <p>Hello, {$message} World!</p>
      </body>
    </html>

    ソースコード(PHP)

    <?php
    require_once 'libs/Smarty.class.php';
    $smarty = new Smarty();
    $smarty->template_dir = 'templates/';
    $smarty->compile_dir  = 'templates_c/';
    $smarty->assign('message', 'Smarty');
    $smarty->display('template.html');
    ?>

    上記の PHP コードならびにテンプレートは実行時に以下の PHP スクリプトに展開される。

    コンパイル結果(PHP)

    <?php /* Smarty version Smarty-3.1.7, created on 2012-01-31 00:10:09
             compiled from "templates/template.html" */ ?>
    <?php /*%%SmartyHeaderCode:10960230224f26b28ceec5c3-38524326%%*/if(!defined('SMARTY_DIR')) exit('no direct access allowed');
    $_valid = $_smarty_tpl->decodeProperties(array (
      'file_dependency' => 
      array (
        '41d3b4a4b71afe0c223778e57c23244caee1baec' => 
        array (
          0 => 'templates/template.html',
          1 => 1327936205,
          2 => 'file',
        ),
      ),
      'nocache_hash' => '10960230224f26b28ceec5c3-38524326',
      'function' => 
      array (
      ),
      'version' => 'Smarty-3.1.7',
      'unifunc' => 'content_4f26b28d05af0',
      'variables' => 
      array (
        'message' => 0,
      ),
      'has_nocache_code' => false,
    ),false); /*/%%SmartyHeaderCode%%*/?>
    <?php if ($_valid && !is_callable('content_4f26b28d05af0')) {function content_4f26b28d05af0($_smarty_tpl) {?><html>
      <head>
         <title>Hello, World!</title>
      </head>
      <body>
        <p>Hello, <?php echo $_smarty_tpl->tpl_vars['message']->value;?> World!</p>
      </body>
    </html>
    <?php }} ?>

    実行方法

    ディレクトリ構成
    /doc               … 公開用フォルダ
        /libs          … ライブラリ配置場所
        /templates     … テンプレート配置場所
        /templates_c   … テンプレートコンパイル結果配置場所
     
    1. ライブラリ(Smarty.class.php)を libs に配置
    2. テンプレート(template.html)を templates に配置
    3. ソース(hello.php)を公開フォルダに配置
    4. ブラウザで表示
       http://localhost/doc/hello.php

    実行結果

    Hello, Smarty World!