def site(template_path, build_path): template_path.join(".ignored1.html").write("Ignored 1") template_path.join("_partial1.html").write("Partial 1") template_path.join("template1.html").write("Test 1") template_path.join("template2.html").write("Test 2") template_path.mkdir("sub").join("template3.html").write("Test {{b}}") template_path.mkdir("sub1").join(".ignored2.html").write("Ignored 2") template_path.mkdir("sub2").join("_partial2.html").write("Partial 2") template_path.mkdir(".ignoreds").join("ignored3.html").write("Ignored 3") template_path.mkdir("_partials").join("partial3.html").write("Partial 3") template_path.join("template4.html").write("Test {{b}} and {{c}}") template_path.mkdir("static_css").join("hello.css").write("a { color: blue; }") template_path.mkdir("static_js").join("hello.js").write( "var a = function () {return true};" ) template_path.join("favicon.ico").write("Fake favicon") contexts = [ ("template2.html", lambda t: {"a": 1}), (".*template3.html", lambda: {"b": 3}), ("template4.html", {"b": 4, "c": 5}), (".*[4-9].html", {"c": 6}), ] rules = [ ("template2.html", lambda env, t, a: None), ] return Site.make_site( searchpath=str(template_path), outpath=str(build_path), contexts=contexts, rules=rules, )
def renderSubjectPages(): # renders pages for all subjects path_to_subject_jsons = './subjects/' subjectLinks = [] for file_name in [ file for file in os.listdir(path_to_subject_jsons) if file.endswith('.json') ]: subject = file_name.replace('.json', '') with open(path_to_subject_jsons + file_name, encoding='utf-8') as json_file: data = json.load(json_file) # download all linked images and chang links to them to use cached local ones data = cacheDownloadAndRelinkImages(data) title = data["title"] subjectLinks.append({"name": title, "href": "/" + subject + "/"}) print("-------- Rendering " + subject + "----------") site = Site.make_site(searchpath="./templates/subjects", outpath="dist/" + subject, env_globals=data) site.render() createManifest(subject, data["title"], data["color"], data["backgroundColor"], '..') return subjectLinks
def render(): if __name__ == "__main__": with open('data.json', 'r', encoding="utf8") as file: context = { 'offers': json.loads(file.read()), } site = Site.make_site(env_globals=context) site.render(use_reloader=True)
def test_render_template_with_env_globals(template_path, build_path): """Ensure variables defined in env_globals can be accessed globally.""" template_name = "template.html" template_path.join(template_name).write("<h1>{{greeting}}</h1>") site = Site.make_site( searchpath=str(template_path), outpath=str(build_path), env_globals={"greeting": "Hello world!"}, ) site.render_template(site.get_template(template_name)) assert build_path.join(template_name).read() == "<h1>Hello world!</h1>"
def render(args): """ Render a site. :param args: A map from command-line options to their values. For example: { '--help': False, '--outpath': None, '--srcpath': None, '--static': None, '--version': False, 'build': True, 'watch': False } """ srcpath = (os.path.join(os.getcwd(), 'templates') if args['--srcpath'] is None else args['--srcpath'] if os.path.isabs(args['--srcpath']) else os.path.join(os.getcwd(), args['--srcpath'])) if not os.path.isdir(srcpath): print("The templates directory '%s' is invalid." % srcpath) sys.exit(1) if args['--outpath'] is not None: outpath = args['--outpath'] else: outpath = os.getcwd() if not os.path.isdir(outpath): print("The output directory '%s' is invalid." % outpath) sys.exit(1) staticdirs = args['--static'] staticpaths = None if staticdirs: staticpaths = staticdirs.split(",") for path in staticpaths: path = os.path.join(srcpath, path) if not os.path.isdir(path): print("The static files directory '%s' is invalid." % path) sys.exit(1) site = Site.make_site(searchpath=srcpath, outpath=outpath, staticpaths=staticpaths) use_reloader = args['watch'] site.render(use_reloader=use_reloader)
def test_followlinks(root_path): # Set up a directory that is outside the searchpath # and put a file in it outside_dir = root_path / "outside" os.mkdir(outside_dir) outside_file = outside_dir / "outside.html" outside_file.write_text("I'm some text!") # Create our searchpath directory, and then create both a # symlink to a file, and a symlink to a directory searchpath = root_path / "src" os.mkdir(searchpath) sym_file = searchpath / "symlink_to_file" os.symlink(outside_file, sym_file) sym_dir = searchpath / "symlink_to_dir" os.symlink(outside_dir, sym_dir) # Regardless of what we set `followlinks`, the `os.walk()` # call that underlies jinja's FileSystemLoader will always # resolve symlinks that point to files. That's just how # `os.walk()` works. # Here we don't resolve directory symlinks. s = Site.make_site(searchpath=searchpath, followlinks=False) assert s.template_names == ["symlink_to_file"] # Here, we resolve both file and directory symlinks. s = Site.make_site(searchpath=searchpath, followlinks=True) assert sorted(s.template_names) == sorted( ["symlink_to_file", "symlink_to_dir/outside.html"]) # If the searchpath itself is a symlink, then we always resolve it. # This again emerges from the behavior of `os.walk()`, where `os.walk(abc)` # always resolves `abc` (the root directory of the walk), regardless of # `followlinks`. sym_searchpath = root_path / "sym_src" os.symlink(outside_dir, sym_searchpath) s = Site.make_site(searchpath=sym_searchpath, followlinks=True) assert s.template_names == ["outside.html"] s = Site.make_site(searchpath=sym_searchpath, followlinks=False) assert s.template_names == ["outside.html"]
def renderHomepage(subjectLinks): # homepage site to copy static files # and link to all subjects print("===> Rendering homepage...") site = Site.make_site(searchpath="./templates/main", outpath="dist/", staticpaths=["static/"], env_globals={ "title": "Hauptseite", "links": subjectLinks }) site.render() createManifest()
def renderpage(): locale.setlocale(locale.LC_ALL, '') data_filepaths = list(collect_data_filepaths()) prices = [] for filename in data_filepaths: with open(filename, 'r') as file: site_price = json.loads(file.read()) prices.extend(site_price) site = Site.make_site(env_globals={ 'prices': prices, }, filters=filters) site.render(use_reloader=False) pathtofile = "index.html" open_file(pathtofile)
def build(): """ Generate a report """ ci_results_context = { "rows": _gen_rows(), "headers": [ datetime.strptime(day, "%Y-%m-%d").strftime("%m-%d") for day in _gen_days() ], "modified": datetime.now(), } site = Site.make_site( contexts=[("index.html", ci_results_context)], outpath="reports/_build" ) site.render() upload_html()
def build(): """ Generate a report """ ci_results_context = { 'rows': _gen_rows(), 'headers': [ datetime.strptime(day, '%Y-%m-%d').strftime('%m-%d') for day in _gen_days() ], 'modified': datetime.now() } site = Site.make_site(contexts=[ ('index.html', ci_results_context), ], outpath='reports/_build') site.render() upload_html()
def test_path_relative_no_warning(root_path): """See sibling test for more info. If someone *is not* relying upon this deprecated behavior, (ie they are supplying relative paths, but build_script_dir==pathlib.Path.cwd(), then they *should not* get a warning. """ entry_point_dir = staticjinja.staticjinja.get_build_script_directory() print(f"entry_point_dir={entry_point_dir}") try: original_cwd = Path.cwd() os.chdir(entry_point_dir) # Sanity check that we are set up properly to actually test this behavior assert Path.cwd() == Path(entry_point_dir) # This should not give a warning or anything searchpath = "relative/path/to/templates" s = Site.make_site(searchpath=searchpath) assert Path(s.searchpath) == Path.cwd() / searchpath finally: os.chdir(original_cwd)
def test_path_relative_warning(root_path): """If a relative path is given to staticjinja, it will try to infer the root of the project. If staticjinja was invoked from a python build script, then SJ will infer the project root is the directory of that build script. This is behavior is deprecated in #149, in the future pathlib.Path.cwd() will always be used. If someone *is* relying upon this deprecated behavior, (ie they are supplying relative paths, and build_script_dir!=pathlib.Path.cwd(), then they *should* get a warning. """ entry_point_dir = staticjinja.staticjinja.get_build_script_directory() print(f"entry_point_dir={entry_point_dir}") print(f"CWD={Path.cwd()}") # Sanity check that we are set up properly to actually test this behavior assert Path.cwd() != Path(entry_point_dir) searchpath = "relative/path/to/templates" with warns(FutureWarning): s = Site.make_site(searchpath=searchpath) assert Path(s.searchpath) == entry_point_dir / searchpath
def render_index_page(): # homepage site to copy static files # and link to all subjects print("===> Rendering Index page...") with open(absol_path_from_build_script('links.json'), encoding='utf-8') as json_file: data = json.load(json_file) # download all linked images and chang links to them to use cached local ones dist_static_path = absol_path_from_build_script('dist/static/') data = cacheDownloadAndRelinkImages(data, dist_static_path) with warnings.catch_warnings(): # ignore this deprecation warning for now warnings.filterwarnings("ignore", message="staticpaths are deprecated. Use Make instead.") # decrease logging to warning loggy = logging.getLogger(__name__) loggy.setLevel(logging.WARNING) made_site = Site.make_site( outpath = absol_path_from_build_script("dist/"), searchpath = absol_path_from_build_script("templates/"), staticpaths = ["static/"], env_globals = data, logger=loggy ) made_site.render() description = None if "description" in data: description = data["description"] # TODO catch missing values and throw good exception # remind to check spelling createManifestForIndex(data["title"], data["short_name"], data["color"], data["background_color"], description)
if __name__ == "__main__": projects = os.listdir('projects') if len(projects) == 2: projects += projects projects += projects projects += projects projects += projects else: projects = sorted(projects, reverse=True) photos = [] k = 0 for photo in projects: k += 1 position_id = k % 24 or 24 class_name = f'photo-{chr(position_id + 96)}' photos.append({'url': photo, 'class': class_name}) index_context = {'page_name': 'index', 'photos': photos, 'photos2': photos} about_context = {'page_name': 'about', 'text': open('texts/about').read()} contact_context = {'page_name': 'contact'} site = Site.make_site(contexts=[ ('index.html', index_context), ('about.html', about_context), ('contact.html', contact_context), ]) site.render( use_reloader=int(sys.argv[1]) == 1 if len(sys.argv) > 1 else False)
('index.html', data), ('results.html', data['MIT300']), ('results_cat2000.html', data['CAT2000']), ] filters = {} md = markdown.Markdown() filters['markdown'] = lambda text: Markup(md.convert(text)) def format_encoded_datetime(datetime_str, format_str): try: datetime_obj = datetime.strptime(datetime_str, '%Y-%m-%dT%H:%M:%S.%f') except ValueError: datetime_obj = datetime.strptime(datetime_str, '%Y-%m-%dT%H:%M:%S') return datetime_obj.strftime(format_str) filters['datetime'] = format_encoded_datetime site = Site.make_site( searchpath='./html/templates', outpath='./html', contexts=contexts, filters=filters, env_kwargs={ 'trim_blocks': True, 'lstrip_blocks': True, } ) site.render()
# d = 'locale' # dirs = [os.path.join(d, o) for o in os.listdir(d) if os.path.isdir(os.path.join(d,o))] # for loc in dirs: # locale = loc.replace('locale/', '') # if locale == 'ja_JP': # loc_name = '/jp' # else: # loc_name = '/' + locale # site = Site.make_site(searchpath='./src', env_globals={"locale": loc_name},locale=locale, extensions=['jinja2.ext.i18n','jinja_markdown.MarkdownExtension']) # # # enable automatic reloading # site.render(use_reloader=False) ###Grabbing blogposts and converting them to feed = feedparser.parse('https://www.docsie.io/blog/rss.xml?skip=1&limit=3').entries feed.reverse() for f in feed: f['link'] = f['link'].replace('/blog/blog/', '/blog/') f['published'] = arrow.get(dateutil.parser.parse(f['published'])).humanize() site = Site.make_site(searchpath='src/', env_globals={"feed":feed[::-1]}, extensions=['jinja2.ext.i18n', 'jinja2.ext.autoescape', 'jinja2.ext.with_','jinja_markdown.MarkdownExtension']) # enable automatic reloading site.render(use_reloader=True)
from staticjinja import Site from tut42_parser import main import datetime def get_date(): cur_date = datetime.datetime.now() return cur_date.strftime('%d/%m/%Y') if __name__ == "__main__": context = {'articles': main()} current_date = {'now': get_date()} site = Site.make_site(contexts=[('index.html', context), ('index.html', current_date)], mergecontexts=True,) site.render(use_reloader=True)
context_projects = {"header_class": "nav-bar", "projects": projects} #Previous Events Page context_prev_events = { "header_class": "nav-bar", "prev_events": prev_events, } # Add Base context to page-specific contexts context_home.update(context_base) context_communities.update(context_base) context_gallery.update(context_base) context_projects.update(context_base) context_prev_events.update(context_base) contexts = [ ("components/_base.html", context_base), ("components/_header.html", context_base), ("index.html", context_home), ("communities.html", context_communities), ("gallery.html", context_gallery), ("showcase.html", context_projects), ("prev_events.html", context_prev_events), ] # StaticJinja site = Site.make_site(contexts=contexts, rules=((r"$_", False), )) # Set reloader to true for hot-reloading. # Set reloader to false before pushing or travis will fail site.render(use_reloader=False)
#!/usr/bin/env python from staticjinja import Site import json import common from guitarTunning import get_guitar from scalaGenerator import get_scale, get_all guitarContext = { "strings": get_guitar(), "notes": common.notes, "jsonNotes": json.dumps(common.notes), "allScales": json.dumps(get_all()) } scaleContext = { "notes": common.notes, "allScales": { "major": [get_scale('major', common.get_note(note)) for note in common.notes], "minor": [get_scale('minor', common.get_note(note)) for note in common.notes] } } site = Site.make_site(contexts=[('guitar.html', guitarContext), ('index.html', scaleContext)], outpath='./docs') site.render()
import json from staticjinja import Site with open('src/index.json', 'r', encoding='utf-8') as fp: index = json.load(fp) with open('src/projects.json', 'r', encoding='utf-8') as fp: projects = json.load(fp) with open('src/research.json', 'r', encoding='utf-8') as fp: research = json.load(fp) with open('src/timeline.json', 'r', encoding='utf-8') as fp: timeline = json.load(fp) contexts = [ ('index.html', dict(**index)), ('projects.html', dict(projects=projects)), ('research.html', dict(research=research)), ('timeline.html', dict(timeline=timeline)), ] if __name__ == "__main__": site = Site.make_site(contexts=contexts) # enable automatic reloading site.render(use_reloader=True)
"content": "60 шт. ПК от 75-15 до ПК 21-15, Криводановка, с доставкой.", "bidder": "Алексей", "phone": "8-999-888-77-66", "views": 12 } bids_amount = 10 bids = generate_placeholder_content(bid, bids_amount) region = 'Новосибирск и область' user_name = 'Леонид Федорович' context = {'bids': bids, 'region': region, 'user_name': user_name} context_part = dict(context) context_part['bids'] = bids[:4] review = { "author": "Кирилл, 29 лет, г.Барабинск", "content": "Бла-бла, мне помогло. Бла-бла, всё супер!" * 4 } reviews_amount = 3 context_part['reviews'] = generate_placeholder_content( review, reviews_amount ) site = Site.make_site( contexts=[ ('index.html', context_part), ('zajavki.html', context) ], outpath='rendered', staticpaths=['assets/css', 'assets/img', 'assets/js'] ) site.render(use_reloader=True)
"""Minimal python build script from https://staticjinja.readthedocs.io/en/stable/user/advanced.html#using-custom-build-scripts """ from staticjinja import Site if __name__ == "__main__": site = Site.make_site() # diable automatic reloading site.render(use_reloader=False)
import json from staticjinja import Site if __name__ == "__main__": with open('data.json', 'r') as file: context = { 'news': json.loads(file.read()), } site = Site.make_site(env_globals=context) site.render(use_reloader=True)
'site_history':data_home['site_history'], 'alumni_description':data_home['alumni_description'], 'services':data_home['services'], 'events': events, 'webinars': webinars, 'open_source_communities': data_home['open_source'], 'eventsP': data_home['eventsP'], 'team': data_home['team'], 'alumini':data_home['alumini'], 'header_class': 'mainHeaderLayout1' } context_communities = { 'header_class': 'mainHeaderLayout', 'communities': communities } context_gallery = { 'header_class': 'mainHeaderLayout' } context_projects = { 'header_class': 'mainHeaderLayout1', 'projects': projects } context_home.update(context_base) context_communities.update(context_base) context_gallery.update(context_base) context_projects.update(context_base) contexts = [('components/_base.html', context_base), ('components/_header.html', context_base), ('index.html', context_home), ('communities.html', context_communities), ('gallery.html', context_gallery), ('showcase.html', context_projects)] #StaticJinja site = Site.make_site(contexts = contexts, rules=((r'$_', False),)) site.render(use_reloader=True)
arg_parser = argparse.ArgumentParser() arg_parser.add_argument("-w", action='store_true', help="Build in watch mode") arg_parser.add_argument("-o", default=BUILD_PATH, help="Output directory path") arg_parser.add_argument("--page", nargs='*', default=[]) arg_parser.add_argument("--post", nargs='*', default=[]) args = arg_parser.parse_args() tmp = Template(new_pages=args.page, new_posts=args.post, datapath=DATA_PATH) site = Site.make_site( searchpath=SOURCE_PATH, outpath=os.path.abspath(args.o), staticpaths=[ "static", "CNAME", "robots.txt" "favicon.ico", "apple-touch-icon.png", "apple-touch-icon-precomposed.png", ], contexts=[ (".*.html", tmp.context()), ("insights/index.html", tmp.insights_context()), ], env_globals=tmp.env_globals(), filters=tmp.filters(), mergecontexts=True, ) # enable automatic reloading site.render(use_reloader=args.w)
#!/usr/bin/env python from staticjinja import Site if __name__ == "__main__": site = Site.make_site(env_globals={ 'BASE_URL':'https://bonsamurais.github.io/bonsai.uno/', }) site.render()
return formatted_price filters = { 'format_price': format_price, } def collect_data_filepaths(directory_path='data', ): for file in os.listdir(directory_path): if file.endswith(".json"): yield os.path.join(directory_path, file) if __name__ == "__main__": locale.setlocale(locale.LC_ALL, '') data_filepaths = list(collect_data_filepaths()) cars = [] for filename in data_filepaths: with open(filename, 'r') as file: site_cars = json.loads(file.read()) cars.extend(site_cars) site = Site.make_site(env_globals={ 'cars': cars, }, filters=filters) site.render(use_reloader=True)
'user_age': 29, 'user_city': 'Барабинск', 'comment_text': """Бла, бла, бла! Мне помогло, все супер! Бла, бла, бла! Мне помогло, все супер! Бла, бла, бла! Мне помогло, все супер!""", } index_data = { 'title': 'Поставщики Новосибирска', 'orders_list': [order for number in range(4)], 'list_of_comments': [comment for number in range(3)], 'need_to_show_notify_message': 1, } index_data.update(main_data) orders_data = { 'title': 'Заявки', 'orders_list': [order for number in range(10)] } orders_data.update(main_data) if __name__ == "__main__": site = Site.make_site(outpath='static', contexts=[('index.html', index_data), ('orders.html', orders_data)] ) site.render(use_reloader=True)
from staticjinja import Site from csscompressor import compress import os OUTPATH = os.environ.get("OUTPATH",default="/var/www/html") APPVERSION = os.environ.get("APPVERSION",default="testBuild") STATIC_PATH = os.environ.get("STATIC_PATH",default="static/") if __name__ == "__main__": site = Site.make_site( env_globals={ "app_version":APPVERSION }, searchpath="./templates", outpath=OUTPATH, staticpaths=[STATIC_PATH] ) site.render() # css compression print("Compressiong CSS files.") for css_file in os.listdir(os.path.join(OUTPATH,STATIC_PATH,"css")): with open(os.path.join(OUTPATH,STATIC_PATH,"css",css_file) ,"r") as f: original_content = f.read() with open(os.path.join(OUTPATH,STATIC_PATH,"css",css_file) ,"w") as f: f.write(compress(original_content))
# # little script used to build static pages # __author__ = 'IU1BOW - Corrado' from staticjinja import Site def cookies_check(): return False if __name__ == "__main__": site = Site.make_site(searchpath="../static/html/templates/", outpath="../static/html/", env_globals={ 'cookies_check': cookies_check, }) site.render(use_reloader=False)
import sass from staticjinja import Site import os import htmlmin if __name__ == "__main__": sass.compile(dirname=("sass/", "../assets/css/"), output_style='compressed') site = Site.make_site(outpath="../", # env_globals={'greeting':'Hello world!',} ) site.render() # os.rename("../index.jinja","../index.html") htmlmin.minify('../index.html') with open('../index.jinja', 'r') as jinja_file: content = htmlmin.minify(jinja_file.read(), remove_empty_space=True, remove_comments=True) if os.path.exists('../index.html'): os.remove('../index.html') os.remove('../index.jinja') with open('../index.html', 'w') as html_file: html_file.write(content)