问题
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?
回答1:
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 }}
回答2:
For example you have the BaseController in your src/Controller
directory.
- You should create BaseController
- Extends it from Controller
- Override render method of the Controller class
- And use this method in every controller
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.
回答3:
Use
{% spaceless %}
YOUR WHOLE PAGE GOES HERE HTML, TWIG, JS EVERYTHING...
{% endspaceless %}
It can be that your twig version does not recognize the tags, just update the latest version of twig.
This will minify the output html generated and page load will go up because it only loads the compiled version of html.
While you can still view the code in a readable situation.
来源:https://stackoverflow.com/questions/18678522/how-can-i-minify-html-with-twig