Learn how to build a static site generator in just 100 PHP lines

Find Saas Video Reviews — it's free
Saas Video Reviews
Makeup
Personal Care

Learn how to build a static site generator in just 100 PHP lines

Table of Contents

1. Introduction

2. Setting up the Static Site Generator

2.1 Creating the Main Class File

2.2 Getting the Content Files

2.3 Choosing the Content Format: JSON

3. Templating with Laravel Blade

3.1 Using Laravel Blade in a PHP Project

3.2 Passing Data to the Template

4. Generating HTML Pages

4.1 Creating the Output Directory Structure

4.2 Saving HTML Files

5. Conclusion

Building a Full-Fledged Static Site Generator with PHP and Laravel Blade

In this article, we will guide you on how to build a powerful static site generator using PHP and Laravel Blade. With just 100 lines of code, you will be able to read content files, process them with a templating engine, and generate static HTML files. This tutorial will walk you through each step, providing clear instructions and helpful code examples.

1. Introduction

Static site generators are becoming increasingly popular for their efficiency and simplicity. By generating HTML files ahead of time, static site generators eliminate the need for server-side processing and allow websites to load faster. In this tutorial, we will build our own static site generator in PHP, leveraging the power of Laravel Blade templating engine.

2. Setting up the Static Site Generator

Before we dive into the details, let's set up the basic structure of our static site generator. We will create a main class file to handle the generation process and define methods for each step.

2.1 Creating the Main Class File

To start, create a file named SSG.php and add the necessary boilerplate code. We will define an initial method that will be called at the end of the file.

class SSG {
    public static function run() {
        // Code here
    }
}

SSG::run();

2.2 Getting the Content Files

The first task is to retrieve the content files for our site. We will store these files in a directory named "content" under the site root. To fetch the files, we can use a simple one-liner:

$files = array_diff(scandir('content'), ['..', '.']);

Next, we need to process the content of each file and extract the necessary information.

2.3 Choosing the Content Format: JSON

In this tutorial, we will use JSON files to store our content data. JSON provides a flexible and structured format that is easy to work with. For example, let's create two test JSON files: index.json for the landing page and about-me.json for the "About Me" page.

/* index.json */
{
    "title": "Welcome to my website",
    "subtitle": "A brief introduction",
    "items": [
        {
            "name": "Item 1",
            "url": "https://example.com/item-1"
        },
        {
            "name": "Item 2",
            "url": "https://example.com/item-2"
        },
        {
            "name": "Item 3",
            "url": "https://example.com/item-3"
        }
    ]
}
/* about-me.json */
{
    "title": "About Me",
    "subtitle": "A little bit about who I am"
}

3. Templating with Laravel Blade

For simplicity and flexibility, we will use Laravel Blade as our templating engine. Laravel Blade offers a clean and intuitive syntax for creating templates and rendering dynamic content. Let's set up the necessary dependencies and integrate Blade into our project.

3.1 Using Laravel Blade in a PHP Project

To use Laravel Blade, we need to install the necessary dependencies using Composer. Add the following line at the very top of your class file to autoload the Composer packages:

require __DIR__ . '/vendor/autoload.php';

Next, we need to import the Blade namespace to access its functionality:

use Philo\Blade\Blade;

3.2 Passing Data to the Template

Now that we have Blade set up, we can start passing data to our templates. In our loop that retrieves content files, we will create a new instance of Blade. We will also pass the data from the JSON file to the template using the getView method.

$blade = new Blade(__DIR__ . '/views', __DIR__ . '/cache');

foreach ($files as $file) {
    $content = json_decode(file_get_contents("content/$file"));
    $html = $blade->view()->make('default', get_object_vars($content))->render();
    // Save HTML to file
}

4. Generating HTML Pages

Now that we have the HTML content generated, let's save it to the correct path and create the directory structure accordingly.

4.1 Creating the Output Directory Structure

To create the directory structure, we will use the slug attribute defined in the JSON files. If the directory does not exist, we will create it using the mkdir function.

$slug = $content->slug;
$outputPath = __DIR__ . '/output/' . $slug;
if (!is_dir($outputPath)) {
    mkdir($outputPath, 0755, true);
}

4.2 Saving HTML Files

To save the generated HTML content to a file, we will use the file_put_contents function. We will append the file name with index.html so that URLs can be accessed directly.

$outputFile = $outputPath . '/index.html';
file_put_contents($outputFile, $html);

5. Conclusion

Congratulations! You have successfully built a static site generator using PHP and Laravel Blade. By following this tutorial, you now have a fully functional generator that can process content files, generate HTML pages, and create a clean directory structure. Experiment with different content formats and templates to further enhance your site. Enjoy the benefits of a fast and efficient static website!

FAQ

Q: Can I use a different templating engine instead of Laravel Blade?

A: Yes, you can choose any templating engine that suits your needs. However, in this tutorial, we focused on Laravel Blade for its simplicity and popularity.

Q: How can I add additional pages to my site?

A: Simply create new JSON files with the desired content and place them in the "content" directory. The static site generator will process them and generate corresponding HTML pages.

Q: Can I include dynamic content or use a database with this static site generator?

A: No, static site generators are designed to generate pre-rendered static HTML pages. If you require dynamic content or database integration, a different approach is recommended.

Q: How can I customize the design of my site?

A: You can modify the Blade templates located in the "views" directory to change the design of your site. Feel free to add CSS stylesheets and images to enhance the visual appeal.

Q: Is it possible to automate the generation process?

A: Yes, you can set up a build script or use a task runner like Gulp or Grunt to automate the generation process. This way, your site will be automatically updated whenever there are changes in the content files.

Q: Are there any limitations to using a static site generator?

A: Static site generators are ideal for simple websites without dynamic functionality. However, if your site requires real-time data updates or user interactions, a dynamic website approach would be more suitable.

Q: Can I host my generated static site on any hosting provider?

A: Yes, you can host your generated static site on virtually any hosting provider that supports static file hosting. Popular options include GitHub Pages, Netlify, and AWS S3.

Q: Is this static site generator suitable for large-scale websites?

A: While this tutorial provides a basic implementation, it can be a starting point for larger projects. For large-scale websites, you may need to consider additional optimizations, caching strategies, and performance improvements.

Q: Are there any security considerations when using a static site generator?

A: Since the static site generator generates static files, there are fewer security concerns compared to dynamic websites. However, it is still important to follow standard security practices and ensure that your hosting environment is secure.

Q: Can I extend this static site generator with additional features?

A: Absolutely! This tutorial covers the basics of building a static site generator, but you can extend it to suit your specific needs. Feel free to add features like custom metadata, pagination, or external data sources to enhance the functionality.

Are you spending too much time on makeup and daily care?

Saas Video Reviews
1M+
Makeup
5M+
Personal care
800K+
WHY YOU SHOULD CHOOSE SaasVideoReviews

SaasVideoReviews has the world's largest selection of Saas Video Reviews to choose from, and each Saas Video Reviews has a large number of Saas Video Reviews, so you can choose Saas Video Reviews for Saas Video Reviews!

Browse More Content
Convert
Maker
Editor
Analyzer
Calculator
sample
Checker
Detector
Scrape
Summarize
Optimizer
Rewriter
Exporter
Extractor