Mixing PHP into Hugo
Hugo is nice because of its blog template system, static
site generation abilities and generic framework structure, but sometimes you may
want to add extra functionality that requires dynamic
PHP
and
Hugo.
If you are also combining static elements with dynamic functions you may want to
DRY
your views to make
everything consistent. It could be that you only want the blog of your website
to be static and everything else to operate dynamically.
We can generate files ending in .php
using the
media types option in
Hugo, however because the template is in the layouts/_default
directory, we
can simply inject something like this directly within the .html
go-html-template
{{ safeHTML "<?php require $_SERVER['DOCUMENT_ROOT'] . '/..' . '/views/partials/navigator.php'; ?>" }}
This tells Hugo when compiling to insert the above PHP
code as
safe HTML into the statically generated
.html
files as PHP
then you are good to
go.
cfg
# nginx let fastcgi parse .php, .html, and .htm
location ~ \.(php|html|htm)$ {
include default.d/php_fastcgi.conf;
}
More tricks can be had by carefully tiptoeing around the Go
PHP
to prevent image reflow.
This can also be done with plain
imageConfig.
go-html-template
{{ safeHTML "<?php" }}
$width = getimagesize($_SERVER['DOCUMENT_ROOT'] . '{{.Get `source`}}')[0];
$height = getimagesize($_SERVER['DOCUMENT_ROOT'] . '{{.Get `source`}}')[1];
$ratio = ((($height / $width) * 100) > 100) ? $height . 'px' : $height / $width * 100 . '%';
{{ safeHTML "?>" }}
<img data-image-zoom src="{{.Get `source`}}" alt="{{.Get `title`}}" title="{{.Get `title`}}"
{{ safeHTMLAttr `<?php echo 'width=' . '"' . $width . '"'; ?>` }}
{{ safeHTMLAttr `<?php echo 'height=' . '"' . $height . '"'; ?>` }} />
If you are interested in producing .php
pages with Hugo, take a
look at using custom output formats.
Note that since Hugo version 0.44
the
MediaType.Suffix
is deprecated and replaced with a plural version,
MediaType.Suffixes