In the world of web development, efficiency is key. As developers, we’re always on the lookout for ways to streamline our processes and save time without sacrificing quality. One area where this can be particularly challenging is in managing frontend templates.
In this blog post, we’ll explore a Python script that automates the conversion of HTML files to Blade templates, a task commonly encountered in Laravel web development. The script, written using Python’s built-in os
module, offers a simple yet effective solution to this common pain point.
We’ll delve into the code, step by step, explaining how it works and how you can adapt it to suit your own projects. By the end of this post, you’ll have a clear understanding of how to leverage automation to enhance your web development workflow, saving time and reducing the potential for human error.
Whether you’re a seasoned developer looking to optimize your processes or a newcomer eager to learn new tricks of the trade, this blog post has something for you. Let’s dive in and discover how you can supercharge your web development workflow with Python automation.
import os
def find_blade_files(directory):
# List all files in the directory
files = os.listdir(directory)
# Filter files that end with '*.blade.php'
blade_files = [file for file in files if file.endswith('.blade.php')]
return blade_files
def convert_html_to_blade(directory):
# List all files in the directory
html_files = [file for file in os.listdir(directory) if file.endswith('.html')]
# Loop through HTML files
for file_name in html_files:
# Read the content of the HTML file
with open(os.path.join(directory, file_name), 'r', encoding='utf-8') as html_file:
html_content = html_file.read()
# Remove the extension .html and add .blade.php
blade_file_name = file_name.replace('.html', '.blade.php')
# Write the HTML content to a new Blade file
with open(os.path.join(directory, blade_file_name), 'w', encoding='utf-8') as blade_file:
blade_file.write(html_content)
# Remove the HTML file
os.remove(os.path.join(directory, file_name))
# Get the directory of the script
directory_path = os.path.dirname(os.path.abspath(__file__))
# Convert HTML files to Blade templates and delete the HTML files
convert_html_to_blade(directory_path)
# Call the function to find blade files in the directory
blade_files = find_blade_files(directory_path)
# Print the names of blade files without the .blade.php extension
print("Blade Files:")
for file in blade_files:
# Split the file name based on the dot (.)
parts = file.split('.')
# Remove the last two parts (blade and php)
filename_without_extension = '.'.join(parts[:-2])
print(f"Route::get('/{filename_without_extension}', function () {{ return view('{filename_without_extension}'); }});")