[Zend Framework] Zend_ControllerへSmarty組み込む (続き)
3月 27th, 2008 Posted in Zend Framework
前回SmartyをZend_Controllerへ組み込みましたが、このままでは出力はエスケープされません。Smartyでの出力のエスケープ処理は以下のようになります。
{$hello|escape:"html"}
view側で出力の都度エスケープ処理を行ってもいいのですが
- 面倒くさい
- ものにもよるけど、エスケープすべき出力のほうが多いのではないか?
- エスケープのもれが怖い
などの理由で(特に1番最後)、デフォルトで出力のエスケープをするように設定しておいたほうが安心です。
対応は簡単です。
コンストラクタでdefault_modifiersというSmarty変数に’escape:”html”‘を設定するだけです。
require_once 'Zend/View/Interface.php'; require_once 'Smarty/Smarty.class.php'; class ViewSmarty implements Zend_View_Interface { protected$_smarty; public function __construct($tmplPath = null, $extraParams = array()) { $this->_smarty = new Smarty; if (null !== $tmplPath) { $this->setScriptPath($tmplPath); } foreach ($extraParams as $key => $value) { $this->_smarty->$key = $value; } // ↓これ $this->_smarty->default_modifiers=array('escape:"html"'); } ... }
では確認してみましょう。
コントローラの内容
class FooController extends Zend_Controller_Action { public function indexAction() { $this->view->hello = "<strong>Hello World</strong>"; } }
ビューの内容
<html>
<head>
<title>hello</title>
</head>
<body>
{$hello}
</body>
</html>出力は以下のようになりました。<strong>タグがエスケープされているので、強調表示されていません。
<strong>Hello World</strong>
HTMLのソースは以下のとおり。成功です。
<strong>Hello World</strong>
エスケープしたくないところでは以下のように書けばOKです。
{$hello|smarty:nodefaults}