I'm using Twig and I'd like to be able to minify the HTML output. How do I do this? I tried {% spaceless %}
, but that requires adding that to all my templates. Can I add minification within the Twig engine?
Use the ob_start() Function With a Callback to Minify HTML Output of the PHP Page. You can use the ob_start() function with a callback to remove whitespaces before and after the tags, comments, and whitespace sequences.
Minification is the process of minimizing code and markup in your web pages and script files. It's one of the main methods used to reduce load times and bandwidth usage on websites. Minification dramatically improves site speed and accessibility, directly translating into a better user experience.
This may help you little.
use html-compress-twig you can compress html,css,js in one package.use composer to install composer require nochso/html-compress-twig
and you have to add Extension with twig by using this code.
$app->extend('twig_theme', function($twig_theme, $ojt) {
$twig_theme->addExtension(new nochso\HtmlCompressTwig\Extension());
return $ojt_theme;});
finally go to your template file add this code.
{% htmlcompress %} ....your coding... {% endhtmlcompress %}
{{ htmlcompress('<ul> <li>') }}
{{ '<ul> <li>'|htmlcompress }}
For example you have the BaseController in your src/Controller
directory.
class BaseController extends Controller {
protected function render($view, array $parameters = array(), Response $response = null)
{
if ($this->container->has('templating')) {
$content = $this->container->get('templating')->render($view, $parameters);
} elseif ($this->container->has('twig')) {
$content = $this->container->get('twig')->render($view, $parameters);
} else {
throw new \LogicException('You can not use the "render" method if the Templating Component or the Twig Bundle are not available. Try running "composer require symfony/twig-bundle".');
}
if (null === $response) {
$response = new Response();
}
$content = preg_replace(array('/<!--(.*)-->/Uis',"/[[:blank:]]+/"),array('',' '),str_replace(array("\n","\r","\t"),'',$content));
$response->setContent($content);
return $response;
}
}
You also can extends BaseController in others controllers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With