こんなヘルパーはどう?

jQuery とか使うとスクリプトが簡単に書けるのでそのページにしか使わないスクリプトが出てくるので、
なるべくそのビュー内でJSスクリプトを書きたい。
っていうようなときにどうだろうとか。


captureJS() で囲った部分がレイアウトの $scripts_for_layout に吐き出されます。
スクリプトタグとか覚えられない人なので(面倒なので)それも吐き出してくれます。
captureCSS() を使うとCSSの部分も $scripts_for_layout に吐き出してくれます。
style タグを覚えられない人なので(面倒なので)それも吐き出してくれます。

    public function capture($mode = null)
    {
        if (self::$buffering) {
            $buf = ob_get_clean();
            if (low($mode) == 'js') {
                $this->Javascript->codeBlock("\n".trim($buf),
                    array('allowCache' => false, 'safe' => false, 'inline' => false));
            } else {
                if (low($mode) == 'css') {
                    $buf = sprintf("<style type=\"text/css\">\n<!--\n%s\n-->\n</style>", trim($buf));
                }
                $view =& ClassRegistry::getObject('view');
                $view->addScript($buf);
            }
            self::$buffering = false;
        } else {
            self::$buffering = ob_start();
        }
    }
    
    /**
     * javascript の開始/終了タグをつけてキャプチャする
     */
    public function captureJS()
    {
        $this->capture('js');
    }
    
    /**
     * css の開始/終了タグをつけてキャプチャする
     */
    public function captureCSS()
    {
        $this->capture('css');
    }


レイアウト

<?php echo $html->docType('html4-strict'); ?>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title><?php echo h($title_for_layout); ?></title>

<?php echo $scripts_for_layout; ?>

</head>
<body>

<?php echo $content_for_layout; ?>

</body>
</html>

ビュー

<?php $helper->captureJS(); ?>
$().ready(function(){
    $('form').submit(function(){
        alert('hoge!');
        return false;
    });
});
<?php $helper->captureJS(); ?>