Skip to content

Output processing ​

The third argument to View::make() and view() is a function the finished HTML passes through before it is returned:

php
view(string $template, array $params = [], callable $callback = null): string

It works for every template type — chunk, file and @INLINE alike.

🔹 Stripping HTML ​

php
view('file:user-card', ['user' => $user], function ($buffer) {
    return strip_tags($buffer);
});

📄 Plain text without <div> and <a> — handy for the text part of an email.

🔹 Minification ​

php
view('file:page', [], function ($buffer) {
    return preg_replace('/\s{2,}|\n/', '', $buffer);
});

📉 Careful with <pre> and <textarea>: whitespace is significant there and this replacement eats it.

🔹 Censoring ​

php
view('file:comment', ['text' => $comment], function ($buffer) {
    return str_ireplace(['idiot', 'moron'], '[censored]', $buffer);
});

🔹 Rewriting absolute paths ​

php
view('file:page', [], function ($buffer) {
    return str_replace('https://example.com/assets/', '/assets/', $buffer);
});

🔁 Useful when moving a site between environments.

php
view('file:page', [], function ($buffer) {
    return preg_replace('/<a (.*?)href="(.*?)"(.*?)>/i', '<a $1href="$2" rel="nofollow"$3>', $buffer);
});

🔍 Against SEO spam in comments and guest content.

The handler must return a string

Its return value replaces the output entirely. Forget the return and the template renders as nothing.

One template, not the whole page

The callback sees the result of this view() call, not the final document. To process the whole page, hook the response rather than the template — see Middleware.

© PageBlocks 2019-present