我正在开发一个自定义 Twig 过滤器,它将您的图像调整为设定的宽度(和自动高度)。
{# TWIG CODE #}
{% set imgpath = page.header.custom.bgimage|first.path %}
<div class="thumb" style="background-image: url({{ url(imgpath|resize(240)) }})"></div>
到目前为止它工作得很好,但是当页面的顺序改变时我遇到了一些错误。我想使用 Grav Debug Bar 进行调试,因为它非常方便并且保持代码干净。
在 Twig 中,您可以简单地使用{{ dump(message) }}
.
不幸的是,调整大小的过程发生在原生 PHP 内部,所以我需要一种将消息从 PHP 输出到 Grav Debug Bar 的方法。
如文档中所述,您可以使用$grav['debugger']->addMessage($this)
.
这在调用 resize Twig 过滤器时会引发错误:
Twig_Error_Runtime
An exception has been thrown during the rendering of a template ("Undefined variable: grav").
为什么变量$grav
未定义?
<?php namespace Grav\Common;
use \Grav\Common\Grav;
use \Grav\Common\Page\Page;
use \RocketTheme\Toolbox\ResourceLocator\UniformResourceLocator;
use \Eventviva\ImageResize;
include_once getcwd().'/user/plugins/resizer/lib/ImageResize.php';
class TwigResizerFilters extends \Twig_Extension
{
private $grav;
public function __construct() {
$this->grav = Grav::instance();
}
public function getName() {
return 'TwigResizeFilters';
}
public function getFilters() {
return [
new \Twig_SimpleFilter( 'resize', [$this, 'resizeImage'] )
];
}
public function resizeImage($mediapath, $maxWidth = 1920) {
if (file_exists($mediapath)) {
// if file exists
if ($currImg = getimagesize($mediapath)) {
// if is image
if (preg_match('(jpg|jpeg|png)', $currImg['mime'])) {
// if file format correct
$resizedFolder = 'images/resized/';
// calculate exact img dimensions for proper naming
$maxHeight = floor(($maxWidth/$currImg[0]) * $currImg[1]);
if (!file_exists($resizedFolder)) {
// create folder if it does not exist
mkdir($resizedFolder, 0777, true);
}
// create filename
$resizedExtension = '.'.pathinfo($mediapath, PATHINFO_EXTENSION);
$resizedFilename = basename($mediapath, $resizedExtension).'@'.$maxWidth.'x'.$maxHeight.$resizedExtension;
if (file_exists($resizedFolder.$resizedFilename)) {
// if file already has been cached, just potput
return $resizedFolder.$resizedFilename;
} else {
// if not cached, resize to desired size
$image = new ImageResize($mediapath);
$image->resize($maxWidth, $maxHeight);
$image->save($resizedFolder.$resizedFilename);
return $resizedFolder.$resizedFilename;
}
} else {
$grav['debugger']->addMessage("File type of ".$mediapath." is not supported.");
}
} else {
$grav['debugger']->addMessage($mediapath." is not an image.");
}
} else {
$grav['debugger']->addMessage("File ".$mediapath." does not exist.");
}
}
private function mergeConfig( Page $page ) {
$defaults = (array) $this->grav['config']->get('plugins.resizer');
if ( isset($page->header()->resizer) ) {
$this->grav['config']->set('plugins.resizer', array_merge($defaults, $page->header()->resizer));
}
}
}