LoginSignup
3
3

More than 5 years have passed since last update.

出力されたHTMLに、テンプレートファイルのパスをコメントとして埋め込む

Posted at

便利そう。CakePHP3.x向けに書いてみた。View::render()系を拡張すればテンプレートにコードを増やさなくても良さそう。

View::element()View::_renderElement()View::_render() という風に呼び出されていたのでView::_render()を拡張してみました。

src/View/AppView.php

<?php
namespace App\View;

use Cake\Core\Configure;
use Cake\View\View;

class AppView extends View
{
    /**
     * {@inheritDoc}
     */
    public function initialize()
    {
    }

    /**
     * {@inheritDoc}
     */
    protected function _render($viewFile, $data = [])
    {
        $content = parent::_render($viewFile, $data);
        if (Configure::read('debug')) {
            $content = $this->addViewPathComment($content, $viewFile);
        }
        return $content;
    }

    /**
     * @param string $content
     * @param string $viewFile
     * @return string
     */
    public function addViewPathComment($content, $viewFile)
    {
        $template = "<!-- START %s -->\n%s\n<!-- END %s -->";
        $content = sprintf(
            $template,
            $viewFile,
            $content,
            $viewFile
        );
        return $content;
    }
}

効能

<?php // src/Template/Sample/index.ctp ?>
<p>This file is index.ctp</p>
<?= $this->element('element1') ?>

<?php // src/Template/Element/element1.ctp ?>
<p>This file is element1.ctp</p>

と書くと出力されたHTMLは

<!-- START /var/www/app/src/Template/Layout/default.ctp -->
<!DOCTYPE html>
<html>

<!-- 中略 -->

<!-- START /var/www/app/src/Template/Sample/index.ctp -->
<p>This file is index.ctp</p>
<!-- START /var/www/app/src/Template/Element/element1.ctp -->
<p>This file is element1.ctp</p>

<!-- END /var/www/app/src/Template/Element/element1.ctp -->
<!-- END /var/www/app/src/Template/Sample/index.ctp -->

<!-- 中略 -->

</html>

<!-- END /var/www/app/src/Template/Layout/default.ctp -->

となります。

3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3