プログラミング言語や環境設定を中心としたパソコン関連の技術メモです。
主にシステム開発中に調べたことをメモしています。TIPS的な位置付けで、気が向いたときにちまちま更新していきます。
Smarty、繰り返し処理の書き方(4):foreach
Smartyにおいて、テンプレート内で繰り返し処理を行うときのお話です。
今回はforeach文相当の処理、その名も「foreach」を見ていきますね。

基本的な書き方はこんな感じφ(--)

{foreach 対象配列 as 値格納変数}
    処理
{/foreach}

もしくは

{foreach 対象連想配列 as key値格納変数 => value値格納変数}
    処理
{/foreach}

例えばこんなコードを書くとφ(--)

■test.php
<?php
    //「Smarty.class.php」をインクルード
    require_once(dirname(__FILE__) . '/smarty/libs/Smarty.class.php');

    //インスタンス作成
    $smarty = new Smarty();

    //ディレクトリ指定
    $smarty->template_dir = dirname(__FILE__) . "/templates";
    $smarty->compile_dir = dirname(__FILE__) . "/templates_c";
    $smarty->cache_dir = dirname(__FILE__) . "/cache";
    $smarty->config_dir = dirname(__FILE__) . "/config";

    //値設定
    $ary = array("a", "b", "c", "d", "e");
    $smarty->assign("val1", $ary);
    $ary2 = array("key1" => "value1", "key2" => "value2", "key3" => "value3");
    $smarty->assign("val2", $ary2);

    //テンプレート表示
    $smarty->display("test.tpl");
?>

■test.tpl
<html>
<head><title></title></head>
<body>

{foreach $val1 as $value}
    {$value},
{/foreach}

<br>

{foreach $val2 as $key => $value}
    {$key}:{$value}<br>
{/foreach}

</body>
</html>

こんな結果になりますφ(--)

a, b, c, d, e,
key1:value1
key2:value2
key3:value3

PHPのforeach文とほぼ同じですね。

あっ、そうそう。
section、forと同様「{foreachelse}」があります。

例えばこんなコードを書くとφ(--)

■test2.php
<?php
    //「Smarty.class.php」をインクルード
    require_once(dirname(__FILE__) . '/smarty/libs/Smarty.class.php');

    //インスタンス作成
    $smarty = new Smarty();

    //ディレクトリ指定
    $smarty->template_dir = dirname(__FILE__) . "/templates";
    $smarty->compile_dir = dirname(__FILE__) . "/templates_c";
    $smarty->cache_dir = dirname(__FILE__) . "/cache";
    $smarty->config_dir = dirname(__FILE__) . "/config";

    //値設定
    $smarty->assign("val3", array());

    //テンプレート表示
    $smarty->display("test2.tpl");
?>

■test2.tpl
<html>
<head><title></title></head>
<body>

{foreach $val3 as $key => $value}
    {$key}:{$value}<br>
{foreachelse}
    値が無いよ

{/foreach}

</body>
</html>

こんな結果になりますφ(--)

値が無いよ

そんな感じ(--)ノ

これにて、Smartyの繰り返し処理、完了\(--)/

その他の繰り返し処理:sectionforwhile
スポンサーリンク
 
このエントリーをはてなブックマークに追加 

category:Smarty  thema:システム開発 - genre:コンピュータ  Posted by ササキマコト