QuickAnswer
by

Dynamic optimization (compacting) of CakePHP3 view output, eliminating indentation and other waste in .ctp output.

Dynamic optimization (compacting) of CakePHP3 view output, eliminating indentation and other waste in .ctp output.

When looping in the view(.ctp) of CakePHP, the indentation of the loop is output as it is, and the HTML size becomes huge.

It is not desirable for HTML to take a long time to render or to have a lot of white space in the browser's source view.

So I thought of a way to optimize the output of view.

Environment for this demonstration

CakePHP3.8

Abandoned study method

You could lose the indentation in .ctp, but that would be a bad idea because it would significantly reduce the readability of the code.

Solutions

Add to src/view/AppView.php

<?php
namespace App\View;
use Cake\View\View;
class AppView extends View {
    public function initialize() {
        /* ... */
    }

    public function render($view = null, $layout = null) {
        $html = parent::render($view,$layout);
        return str_replace(["\t","\r",">\n<"],['','','><'],$html);
    }
}

What I added was function render.

If you write it like this, you can add some modifications to the HTML output.

Conditions and cautions for this project

All indentations must be written in tabs.

Can't I just delete tabs and line breaks?

Deleting tabs is no problem, but if you are using tabs as part of a text element, such as using tabs instead of spaces, you need to convert the tabs that should not disappear to spaces.
This would be fine, since there is no point in using tabs as text elements in the first place.

It's usually not a problem if you remove a line break entirely.
However, if JavaScript is written inline, and inline comments are included, the JavaScript code will be broken.
Therefore, only the line breaks in the gaps between the HTML tags are removed.

Execution example

source

<!doctype html>
<html>
<head>
    <meta charset="utf-8">
</head>
<body>
    <h1>test</h1>
    <div>
        <p>text</p>
    </div>
    <script>
    //comment
    var _example = 1;
    </script>
</body>
</html>

conversion result

<!doctype html><html><head><meta charset="utf-8"></head><body><h1>test</h1><div><p>text</p></div><script>
//comment
var _example = 1;
</script></body></html>

What a beautiful and compact design!

application

It is possible for HTML to add, delete, or rewrite something when certain conditions are met.

CONTENTS
Web Browser