Mixing PHP into Hugo

Hugo’s Homepage

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 The unholy union of 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 This is not recommended if you do not have complete control of your stack.

{{ 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 When in the context of an HTML attribute you can use safeHTMLAttr. If your web server is set up to parse .html files as PHP then you are good to go.

# 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 This is blasphemy … is what you are probably thinking. You get the best (or worst) of both This is a partial snippet of an image shortcode which automatically sets height and width using PHP to prevent image reflow. This can also be done with plain imageConfig.

{{ 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

1 August 2018 — Written
18 May 2019 — Updated
Thedro Neely — Creator
mixing-php-into-hugo.md — Article

More Content


On the Web