#!/usr/bin/env python3 class AllPawCare(object): """ Builder for www.allpawcare.com Builds www.allpawcare.com static resources. """ def __init__(self): # Directory variables self.CGI_DIR = 'cgi-bin' self.IMG_DIR = 'img' self.PUBLIC_DIR = 'public' self.TEMPLATES_DIR = 'templates' self.CGI_PUBLIC_DIR = self.PUBLIC_DIR + '/' + self.CGI_DIR self.IMG_PUBLIC_DIR = self.PUBLIC_DIR + '/' + self.IMG_DIR # Types of templates to render self.RENDERED_TYPES = ['forms', 'pages'] # Year to copyright the rendered templates from datetime import datetime self.CURRENT_YEAR = datetime.today().strftime('%Y') # Setup Jinja environment from jinja2 import Environment, FileSystemLoader self.JINJA_ENV = Environment(loader=FileSystemLoader(self.TEMPLATES_DIR)) def __enter__(self): return self def __get_name_map(self): """ Map page templates to page titles. Returns dictionary mapping page templates to page titles. """ name_map = dict() for t in self.JINJA_ENV.list_templates(): t_type = t.partition('/')[0] t_name = t.partition('/')[2] # Only consider page templates if t_type == 'pages': # TEMPLATE: PAGETITLE name_map[t_name] = t_name.removesuffix('.html') return name_map def copy_static_resources(self): """ Copy static assets to public directory. Copies CGI and image resources to public directory. """ import shutil print('Copying static assets...') try: # Copy cgi scripts to public dir shutil.copytree(self.CGI_DIR, self.CGI_PUBLIC_DIR) # Copy images to public dir shutil.copytree(self.IMG_DIR, self.IMG_PUBLIC_DIR) except: print("Error copying static files. Does the public directory exist?") def render_site(self): """ Render site template to static HTML Render www.AllPawCare.com static site from jinja template. """ name_map = self.__get_name_map() for t in self.JINJA_ENV.list_templates(): t_type = t.partition('/')[0] if t_type in self.RENDERED_TYPES: print('Rendering {}'.format(t)) output_file = '{}/{}'.format(self.PUBLIC_DIR, t) with open(output_file, 'w+') as file: template = self.JINJA_ENV.get_template(t) t = template.render(pages=name_map, current_year=self.CURRENT_YEAR) file.write(t) builder = AllPawCare() builder.copy_static_resources() builder.render_site()