Jekyll is a convenient and yet powerful tool to build static web pages. It is instrumental in combination with automatic deployment via GitHub or GitLab pages. You might have noticed that this blog is made using Jekyll. However, sometimes, you want to add a bit of server-side logic to the website. It might be as simple as a contact form or a comment box. In contrast to other online resources that suggest embedding third-party services with JavaScript, this article illustrates how to combined server-side PHP with Jekyll.

The codebase of a Jekyll site usually consists of configuration files, assets, HTML files that serve as layout templates, and the actual content files in Markdown. The framework allows HTML tags in the Markdown source code, which is convenient if you occasionally need a bit more styling or layout flexibility. The Markdown files are equipped with a YAML front matter, which defines metadata such as the page’s title and sets the desired layout template. Jekyll takes the source files and converts them into a set of HTML files and their assets.

If HTML survives Markdown processing, so does PHP code? Yes. However, you need a persuade your webserver to execute the PHP code. For static websites deployed as GitHub or GitLab pages, this will not succeed. The underlying web servers only serve static content.

However, most web servers that support PHP pass the file to the engine if it has a specific file extension, such as .php. It seems like the file extension for converted Markdown in Jekyll is hard-coded to .html. However, it is possible to create a file ending in .php with a YAML header and mixed HTML and PHP code. Jekyll will embed the contents into the assigned template and preserve the PHP code and the file extension.

Here’s an example, let say, example.php:

layout: post
title: Example PHP

  The current date and time is <?php echo date("Y-m-d H:i:s"); ?>.

The static output of Jekyll contains the PHP tags, ready for a web server to execute.