tohokuaikiのチラシの裏

技術的ネタとか。

Smartyの改行について調べてみた

PHP自体もですが、Smarty使っててあー、この{/if}の終わりの改行って表示されんのかな?とか結構気になる時があります。

普通にHTMLなら問題ないのですが、メールテンプレートとして使った時です。

ということで、調べてみました。

実行するテストスクリプト

<?php
require_once 'Smarty/Smarty.class.php';
$smarty = new Smarty();
$smarty->template_dir = dirname(__FILE__);
$smarty->compile_dir  = dirname(__FILE__)."/tmp";
$smarty->left_delimiter = '<{';
$smarty->right_delimiter = '}>';
$smarty->force_compile = true;
$smarty->assign('array', range(1,3));

$tpl = "smarty_test.tpl";

echo "*******テンプレート*******\n";
echo file_get_contents($tpl);
echo "\n*******出力結果******\n";

$smarty->display($tpl);

Smartyは最後の改行コードを取る

ソース
<{if true}>
HERE is TRUE
<{elseif true}>
HERE is ELSE IF
<{else}>
HERE is ELSE
<{/if}>
------------
sentence1
出力

HERE is TRUE

                      • -

sentence1

なのですが、実際には出力は
最後の改行コードがありません。こんな感じ。

開始IF、閉じIFの次の改行コードは削除される

ソース
<{if true}>HERE is TRUE<{/if}>
------------
sentence1
出力

HERE is TRUE------------
sentence1

なので、当然ELSEとかでも

ソース

<{if false}>
HERE is TRUE<{elseif true}>
HERE is ELSE IF<{else}>
HERE is ELSE<{/if}>

                      • -

sentence1

出力

HERE is ELSE IF

                      • -

sentence1

こうなる。

ソース
<{if false}>
HERE is TRUE
<{elseif false}>
HERE is ELSE IF
<{else}>
HERE is ELSE
<{/if}>
------------
sentence1
出力

HERE is ELSE

                      • -

sentence1

foreachの開始、閉じの直後の改行も無視される

ソース
<{foreach from=$array item=item}>
<{$item}>
<{/foreach}>
------------
sentence1
出力

1
2
3

                      • -

sentence1

まとめ

気付いた。
ブロックの開始と終了のタグの直後のものは無視されるってコトか・・・・。