How to compress the output of an HTML in Laravel?

Asked

Viewed 322 times

3

I answered that question here once talking about the subject:

Store PHP script output in HTML "compressed".

But now I’d like to know how I can do it in Laravel.

When it comes to an HTML response, how could I capture the entire rendering of the views, before it is sent to the browser, and respond to it compressed?

Where could I set this on Laravel 5?

In the above answer already has the solution of how to compress, however I would like to know where I would perform this action in Laravel, in the most appropriate way, to treat the content that goes to data output, before going to the client (browser)?

2 answers

3


Assuming you use Laravel 5.2 you can use the method render, then in Controller would look something like, this is an example just to show how to use it, I switched the $data content for a new output with the return:

<?php

namespace App\Http\Controllers;

use App\User;
use App\Http\Controllers\Controller;

class UserController extends Controller
{
    public function home()
    {
        $v = view('welcome')->render(function ($obj, $data) {
            return 'Hello world!';
        });

        return $v;
    }
}

So just match the other code /a/102364/3635 getting something like:

function reduzirHtml($data)
{
    $search = array(
        '/\>[^\S ]+/s',  // strip whitespaces after tags, except space
        '/[^\S ]+\</s',  // strip whitespaces before tags, except space
        '/(\s)+/s'       // shorten multiple whitespace sequences
    );

    $replace = array(
        '>',
        '<',
        '\\1'
    );

    return preg_replace($search, $replace, $data);
}

class UserController extends Controller
{
    public function home()
    {
        return view('welcome')->render(function ($obj, $data) {
             return reduzirHtml($data);
        });
    }

    public function about()
    {
        return view('welcome')->render(function ($obj, $data) {
             return reduzirHtml($data);
        });
    }
}

If you change the function to function reduzirHtml($obj, $data) can call directly:

return view('welcome')->render("\\App\\Http\\Controllers\\reduzirHtml");

Or you can even move the function reduzirHtml for a file or method in a class and call it as in the example:

//Função
return view('welcome')->render("\\reduzirHtml");

//Classe
return view('welcome')->render("\\Namespace\\Classe\\reduzirHtml");

1

To capture all HTML output of the application, you can also use a Middleware, who will take care of this pre-processing.

First run the command:

 php artisan make:middleware HtmlCompressor

Then leave the method handle as in the example below:

namespace App\Http\Middleware;

use Closure;

/**
 * 
 * @author Wallace de Souza Vizerra <[email protected]>
 * 
 * */
class HtmlCompressor
{

    public function handle()
    {
        $response = $next($request);

        // Verifica se a saída é HTML

        if (str_contains($response->headers->get('content-type'), 'text/html')) {

            $search = [
                '/\>[^\S ]+/s',  // strip whitespaces after tags, except space
                '/[^\S ]+\</s',  // strip whitespaces before tags, except space
                '/(\s)+/s'       // shorten multiple whitespace sequences
            ];

            $replace = [
                '>',
                '<',
                '\\1'
            ];

            $response->setContent(preg_replace($search, $replace, $response->getContent()));

            return $response;

        }

        return $response;
    }
}

In class App\Http\Kernel of your application, you will add this middewlare that we create in the property $middleware:

protected $middleware = [
   // outros middlewares
   \App\Http\Middleware\HtmlCompressor
];
  • 1

    I would mark this as the correct one because it is smarter, I mean it detects if the output is really html and on top of that is organized in a separate file and at the same time is automated.

  • Your answer is good yes. I only answered with alternative of a "global treatment"

  • I know :) ... I just meant that your being smarter is the best alternative, but it doesn’t mean mine is bad. The problem with my answer is who uses it, the thing is "loose", a user with less experience would probably end up disorganizing things or even replicating several function, this for same inexperience ;)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.