Wadslog

[Zend Framework] Zend_ControllerへSmarty組み込む (続き)

Mar 26, 2008

前回SmartyをZend_Controllerへ組み込みましたが、このままでは出力はエスケープされません。Smartyでの出力のエスケープ処理は以下のようになります。``` {$hello|escape:“html”}


*   面倒くさい
*   ものにもよるけど、エスケープすべき出力のほうが多いのではないか?
*   エスケープのもれが怖い

などの理由で(特に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>";
    }
}

```ビューの内容```


hello

{$hello}



```出力は以下のようになりました。<strong>タグがエスケープされているので、強調表示されていません。```
**Hello World**

```HTMLのソースは以下のとおり。成功です。```
<strong>Hello World</strong>

```エスケープしたくないところでは以下のように書けばOKです。```
{$hello|smarty:nodefaults}

comments powered by Disqus