コード例 #1
0
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.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 make_site(searchpath=str(template_path),
                     outpath=str(build_path),
                     contexts=contexts,
                     rules=rules)
コード例 #2
0
def build_site(lang):
    context = {'LANG': lang, 'DIR': text_dir(lang)}

    outpath = os.path.join(renderpath, lang)
    if not os.path.exists(outpath):
        os.makedirs(outpath)
    site = make_site(outpath=outpath,
                     searchpath=searchpath,
                     extensions=extensions,
                     env_globals=context)

    translator = translate.Translation(lang,
                                       ['thunderbird/start/release', 'main'])
    gettext_translator = translate.gettext_object(lang)
    site._env.install_gettext_translations(gettext_translator)

    def l10n_has_tag(tag):
        return tag in translator.lang_file_tag_set('thunderbird/start/release',
                                                   lang)

    # Add l10n_css function to context
    site._env.globals.update(l10n_css=translator.l10n_css,
                             l10n_has_tag=l10n_has_tag,
                             **helper.contextfunctions)
    site.render(use_reloader=False)
    shutil.rmtree(renderpath + '/media', ignore_errors=True)
    shutil.copytree(staticpath, renderpath + '/media')
コード例 #3
0
def build_site(lang):
    version = helper.thunderbird_desktop.latest_version('release')
    context = {'LANG': lang,
               'DIR': text_dir(lang),
               'platform': 'desktop',
               'query': '',
               'platforms': helper.thunderbird_desktop.platforms('release'),
               'full_builds_version': version.split('.', 1)[0],
               'full_builds': helper.thunderbird_desktop.get_filtered_full_builds('release', helper.thunderbird_desktop.latest_version()),
               'channel_label': 'Thunderbird',
               'releases': helper.thunderbird_desktop.list_releases()
                }

    outpath = os.path.join(renderpath, lang)
    if not os.path.exists(outpath):
        os.makedirs(outpath)
    site = make_site(outpath=outpath, searchpath=searchpath, extensions=extensions, env_globals=context)

    translator = translate.Translation(lang, ['thunderbird/index', 'thunderbird/features', 'thunderbird/channel', 'main'])
    site._env.install_gettext_translations(translator)

    def l10n_has_tag(tag):
        return tag in translator.lang_file_tag_set('thunderbird/features', lang)

    # Add l10n_css function to context
    site._env.globals.update(translations=translator.get_translations(), l10n_css=translator.l10n_css, l10n_has_tag=l10n_has_tag, settings=settings, **helper.contextfunctions)
    site.render(use_reloader=False)

    # Render release notes and system requirements for en-US only.
    if lang == settings.LANGUAGE_CODE:
        notelist = releasenotes.notes
        e = site._env
        e.filters["markdown"] = helper.safe_markdown
        e.filters["f"] = helper.f
        e.filters["l10n_format_date"] = helper.l10n_format_date
        template = e.get_template('_includes/release-notes.html')
        e.globals.update(feedback=releasenotes.settings["feedback"], bugzilla=releasenotes.settings["bugzilla"])
        for k, n in notelist.iteritems():
            if 'beta' in k:
                e.globals.update(channel='Beta')
            else:
                e.globals.update(channel='Release')
            n["release"]["release_date"] = n["release"].get("release_date", helper.thunderbird_desktop.get_release_date(k))
            n["release"]["release_date"] = parse(str(n["release"]["release_date"]))
            e.globals.update(**n)
            target = os.path.join(outpath,'thunderbird', str(k), 'releasenotes')
            mkdir(target)
            with open(os.path.join(target, 'index.html'), "wb") as f:
                print "Rendering {0}/index.html...".format(target)
                o = template.render()
                f.write(o.encode('utf8'))

            target = os.path.join(outpath,'thunderbird', str(k), 'system-requirements')
            mkdir(target)
            newtemplate = e.get_template('_includes/system_requirements.html')
            with open(os.path.join(target, 'index.html'), "wb") as f:
                print "Rendering {0}/index.html...".format(target)
                o = newtemplate.render()
                f.write(o.encode('utf8'))
コード例 #4
0
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 = staticjinja.make_site(
        searchpath=srcpath,
        outpath=outpath,
        staticpaths=staticpaths
    )

    use_reloader = args['watch']

    site.render(use_reloader=use_reloader)
コード例 #5
0
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 = 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>'
コード例 #6
0
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 = 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>'
コード例 #7
0
ファイル: gensite.py プロジェクト: internaut-me/btcresearch
def main():
    global entries

    s = make_site(contexts=[('.*.json', load_publication),
                            ('index.html', load_entries)],
                  rules=[
                      ('.*.json', render_publication),
                  ],
                  outpath='output',
                  staticpaths=('static/', ))
    s.render()
コード例 #8
0
ファイル: manage.py プロジェクト: TimBest/timbest.net
    def run(self):
        site = make_site(
            searchpath=config.SITE_DIRECTORY,
            outpath=config.OUTPUT_DIRECTORY,
            staticpaths=[config.STATIC_PATH],
            contexts=self.get_contexts(),
            env_globals={"static": lambda x: "/%s%s" % (config.STATIC_PATH, x)},
            rules=[("templates/*", preprocess_templates)],
            extensions=["pypugjs.ext.jinja.PyPugJSExtension"],
        )

        site.render()
コード例 #9
0
ファイル: cli.py プロジェクト: vapopov/lightning-integration
def html():
    global entries

    s = make_site(contexts=[
        ('index.html', load_reports),
        ('.*.json', load_report),
    ],
                  rules=[
                      ('.*.json', render_report),
                  ],
                  outpath='output',
                  staticpaths=('static/', ))
    s.render()
コード例 #10
0
ファイル: gensite.py プロジェクト: cdecker/btcresearch
def main():
    global entries

    s = make_site(
        contexts=[
            ('.*.json', load_publication),
            ('index.html', load_entries),
            ('cabra.bib', load_entries),
        ],
        rules=[
            ('.*.json', render_publication),
        ],
        outpath='output',
        staticpaths=('static/',),
    )
    s.render()
コード例 #11
0
ファイル: gen.py プロジェクト: s270987763/PyConChina2016
def create_site(debug=False, use_reloader=False, generate=False):
    _init_dirs()
    assets_env = _init_webassets(debug=debug, generate=generate)

    for lang, context in data_contexts.iteritems():
        context['printlog'] = _sp_printlog
        context['selectspeakers'] = _sp_selectspeakers

    site = make_site(searchpath=SITE_SRC_DIR,
                     staticpaths=[REL_SITE_ASSET_DIR],
                     outpath=SITE_DIR,
                     extensions=[AssetsExtension],
                     rules=[("[\w-]+\.html", _render_page)])

    # HACK: staticjinja没有提供 jinja2.Environment 的引用,
    # 因此这里只能访问其私有属性进行设置
    site._env.assets_environment = assets_env
    site.render(use_reloader=use_reloader)
コード例 #12
0
ファイル: gen.py プロジェクト: jackzhangpython/PyConChina2016
def create_site(debug=False, use_reloader=False):
    _init_dirs()
    assets_env = _init_webassets(debug=debug)

    for lang, context in data_contexts.iteritems():
        context['printlog'] = _sp_printlog
        context['selectspeakers'] = _sp_selectspeakers

    site = make_site(searchpath=SITE_SRC_DIR,
                     staticpaths=[REL_SITE_ASSET_DIR],
                     outpath=SITE_DIR,
                     extensions=[AssetsExtension],
                     rules=[
                         ("[\w-]+\.html", _render_page)
                     ])

    # HACK: staticjinja没有提供 jinja2.Environment 的引用,
    # 因此这里只能访问其私有属性进行设置
    site._env.assets_environment = assets_env
    site.render(use_reloader=use_reloader)
コード例 #13
0
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.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 make_site(searchpath=str(template_path),
                     outpath=str(build_path),
                     contexts=contexts,
                     rules=rules)
コード例 #14
0
ファイル: build.py プロジェクト: GovLab/www.thegovlab.org
    subprocess.check_call(
        'git subtree push --prefix site origin gh-pages',
        shell=True
    )

if __name__ == '__main__':
    context = ReloadingContext()

    site = staticjinja.make_site(
        filters=filters(),
        outpath=_OUTPUTPATH,
        contexts=[
            (r'.*.html', context.get),
            (r'project-detail-pages.custom', context.get),
        ],
        rules=[
            (r'project-detail-pages.custom', render_project_detail_pages)
        ],
        searchpath=_SEARCHPATH,
        staticpaths=['static']
    )

    manager = Manager(
        sass_src_path=path.join(_SASSPATH, 'styles.scss'),
        sass_dest_path=path.join(_SEARCHPATH, 'static', 'styles',
                                 'styles.css'),
        site=site,
        site_name='www.thegovlab.org',
    )
    context.add_to(manager)
コード例 #15
0
from filters import *
from funcs import *

# Remove existing build directory or fail silently
try:
	shutil.rmtree(config.build)
except:
	pass

# Copy static files into build
copy_tree('static/', '%s/' % (config.build))

# Build standard pages
site = config.site = make_site(
	searchpath=config.templates,
	filters=filters,
	contexts=[(r'.*', funcs)],
	env_kwargs=dict(trim_blocks=True, lstrip_blocks=True),
	outpath=config.build)
site.render()

# Build rule based pages

def render(template, dump, **kwargs):
	''' Render custom page with jinja template engine '''
	print('Rendering %s...' % (dump))
	site.get_template(template).stream(**dict(funcs, **kwargs)).dump(os.path.join(config.build, dump))

def render_rules(rules):
	''' Given a rule dictionary, call render as specified
	Rule format:
		{
コード例 #16
0
ファイル: build.py プロジェクト: domogik/domogik-website
        # clean root folder for the lang
        shutil.rmtree(dir)

        # copy static files
        shutil.copytree(STATIC_DIR, dir)

        ### list blog files
        # notice that we assume that the blog entries can be different between each language, so they are not translated over transifex !
        blog_headers = get_blog_headers(lang)

        ### build website
        site = make_site(
            contexts=[
                ("index.html", {"blog_headers": blog_headers}),
                ("blog.html", {"blog_headers": blog_headers}),
                ("screenshots.html", {"screenshots": screenshots}),
            ],
            outpath=dir,
            extensions=["jinja2.ext.i18n"],
        )
        translations = gettext.translation(domain="website", localedir=LOCALE_DIR, languages=[lang], codeset="utf-8")
        site._env.install_gettext_translations(translations)

        site.render()

        ### build blog entries
        blog_dir = "./{0}-{1}".format(BLOG_DIR_PREFIX, lang)
        # copy the layout file in the blog source folder
        shutil.copy(os.path.join(TEMPLATES_DIR, "layout.html"), blog_dir)
        ##"""
        ##os.mkdir(os.path.join(dir, blog_dir))
コード例 #17
0
def site(template_path, build_path):
    """
    Provides a site with the following dependency structure
    (all arrows pointing upward):
    t1    t2
      \  / |
       p1  |  sub.t3
      /| \ | /
    d1 |  p2    t4
       |    \  /
      d2   data.d3
    each t is a template, p is a partial and d is a data file.
    There is also an ignored file .ignored1.html and a static files
    in static_js/ static_css/ and favicon.ico
    """

    template_path.join('.ignored1.html').write('Ignored 1')
    template_path.join('_partial1.html').write(
            'Partial 1\n'
            '{% block content %}{% endblock -%}\n'
            '{% import "_partial2.html" as p2 %}'
            )
    template_path.join('_partial2.html').write('Partial 2')
    template_path.join('template1.html').write(
            '{% extends "_partial1.html" %}\n'
            '{% block content %}Template 1{% endblock -%}'
            )
    template_path.join('template2.html').write(
            '{% extends "_partial1.html" %}\n'
            '{% block content %}Test 2{% endblock -%}\n'
            '{% include "_partial2.html" %}'
            )
    template_path.mkdir('sub').join('template3.html').write(
            'Test {{b}}\n'
            '{% include "_partial2.html" %}'
            )
    template_path.join('template4.html').write('Template {{b}} and {{c}}')

    template_path.join('data1').write('Data 1')
    template_path.join('data2').write('Data 2')
    template_path.mkdir('data').join('data3').write('Data 3')

    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')

    staticpaths = ["static_css", "static_js", "favicon.ico"]
    datapaths = ["data", "data/data3"]
    extra_deps = {
            '_partial1.html': ['data1', 'data2'],
            '_partial2.html': ['data/data3'],
            'template4.html': ['data/data3'],
            }
    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 make_site(searchpath=str(template_path),
                     outpath=str(build_path),
                     contexts=contexts,
                     rules=rules,
                     staticpaths=staticpaths,
                     datapaths=datapaths,
                     extra_deps=extra_deps,
                     )
コード例 #18
0
from staticjinja import make_site
import json


if __name__ == "__main__":

    site = make_site(
        searchpath="site/templates",
        outpath="site/",
        env_globals=json.load(open('site/data.json')),
    )

    # enable automatic reloading
    site.render(use_reloader=True)
コード例 #19
0
ファイル: build.py プロジェクト: stalwart201/inpycon2016
#!/usr/bin/env python
from __future__ import absolute_import, unicode_literals

import json

from staticjinja import make_site


def get_schedule(file_path='data/schedule.json'):
    with open(file_path) as data_file:
        return json.load(data_file)


if __name__ == "__main__":
    site = make_site(contexts=[
        ('index.html', {
            "schedule": get_schedule()
        })
    ])
    # enable automatic reloading
    site.render(use_reloader=True)
コード例 #20
0
ファイル: build.py プロジェクト: Ceasar/staticjinja
import staticjinja


if __name__ == "__main__":
    site = staticjinja.make_site()
    site.render()
コード例 #21
0
    # compile SASS style sheets
    run("sass --update --force --style=compact --sourcemap=none sass:static/styles",
        shell=True)

    # clear build directory

    try:
        rmtree("./www")
    except FileNotFoundError:
        pass

    mkdir("./www")

    # render jinja templates

    site = make_site(searchpath="./source",
                     outpath="./www",
                     staticpaths=["./static"])

    site._env.trim_blocks = True
    site._env.lstrip_blocks = True

    site.render()

    # copy static resources
    copytree("./static", "./www/static/")

    # todo: give decent error on failure
    # todo: recursion into sub-directories
    run("tidy -config tidy.txt -modify www/*.html", shell=True)
コード例 #22
0
ファイル: build.py プロジェクト: benwei/Learnings
from staticjinja import make_site

def get_temps():
    """Generate knights of the round table."""
    temp_vars = [
            'item a',
            'item b',
            'item c',
            ]
    return {
            'vars': temp_vars,
            'static_root': '/static'
           }

if __name__ == "__main__":
    site = make_site(contexts=[
        ('index.html', get_temps),
        ])
    site.render(use_reloader=False)
コード例 #23
0
ファイル: test.py プロジェクト: samgriesemer/panja
    opath = os.path.join(site.outpath, template.name)
    opath = opath.split('.')
    opath[-1] = 'html'
    opath = '.'.join(opath)

    template = site.env.get_template('_article.html')
    context = {'article': article}
    template.stream(context).dump(opath)


site = staticjinja.make_site(searchpaths=['theme', 'pages', 'notes'],
                             outpath='output',
                             staticpaths=[
                                 'static/',
                                 'docs/',
                                 'images/',
                                 'projects/dashboard/',
                                 'projects/evolution-art/',
                                 'projects/evolution/',
                                 'projects/halton/',
                                 'projects/mcttt/',
                                 'projects/nn/',
                                 'projects/time-graph/',
                             ],
                             basepath='staticjinja/test',
                             contexts=[('tindex.html', process_articles)],
                             rules=[
                                 ('.*.md', render_article),
                             ])
site.render(use_reloader=True)
コード例 #24
0
ファイル: build.py プロジェクト: GovLab/academy-website
    Deploy the site.
    '''

    subprocess.check_call(
        'git subtree push --prefix site origin gh-pages',
        shell=True
    )


site = make_site(
    filters=filters,
    outpath=outputpath,
    contexts=[
        (r'.*.html', loadAcademyData),
        (r'.*.custom', loadAcademyData),
    ],
    rules=[
        (r'coaching-detail-pages.custom', render_coaching_detail_pages),
        (r'project-detail-pages.custom', render_project_detail_pages),
    ],
    searchpath=searchpath,
    staticpaths=['static', '../data'],
)

manager = Manager(
    site_name='govlabacademy.org',
    site=site,
    sass_src_path=path.join(ROOT_DIR, 'sass', 'styles.scss'),
    sass_dest_path=path.join(searchpath, 'static', 'styles',
                             'styles.css')
)
コード例 #25
0
        rmtree(_OUTPUTPATH)

    # Remake the output folder.
    makedirs(_OUTPUTPATH)


if __name__ == '__main__':
    auto = _AUTO_RELOAD
    ctxt = context()
    site = {}

    cleanup()

    # Accept CLI parameter to turn the auto reloader on and off.
    if len(argv) == 2:
        arg = argv[1].lower()

        if arg in ['0', 'false', 'off', 'no']:
            auto = False

        elif arg in ['1', 'true', 'on', 'yes']:
            auto = True

    site['filters'] = filters()
    site['outpath'] = _OUTPUTPATH
    site['contexts'] = [(r'.*.html', lambda: ctxt)]
    site['searchpath'] = _SEARCHPATH
    site['staticpaths'] = ['static']

    make_site(**site).render(use_reloader=auto)
コード例 #26
0
ファイル: create_site.py プロジェクト: Ranc58/22_proto_markup
    'Криводановка, с доставкой.',
    'request_person_name': 'Алексей',
    'views_value': '12 просмотров',
    'footer': True
}

specification_content = {
    'user': USER,
    'specification': 'ЖБИ',
    'tables': 4,
    'company_name': 'ООО Строй-Сервис-Монтаж',
    'company_location': 'Новосибирск',
    'company_production': 'ЖБИ, бетон',
    'company_address': 'Под часами, на том же месте',
    'company_phone_number': '00-00-00',
    'footer': True
}

profile_content = {'user': USER, 'footer': False}

if __name__ == "__main__":
    site = sj.make_site(outpath='static',
                        contexts=[('index.html', index_content),
                                  ('org_catalog.html', org_catalog_content),
                                  ('organisation.html', organisation_content),
                                  ('profile.html', profile_content),
                                  ('requests.html', requests_content),
                                  ('specification_catalog.html',
                                   specification_content)])
    site.render()
コード例 #27
0
ファイル: build.py プロジェクト: GovLab/govlab-static-tools
import os

import staticjinja
from govlabstatic.cli import Manager

manager = Manager(
    site_name='example site',
    site=staticjinja.make_site(outpath='site'),
    sass_src_path=os.path.join('sass', 'styles.scss'),
    sass_dest_path=os.path.join('site', 'static', 'styles', 'styles.css')
)

if __name__ == '__main__':
    manager.run()
コード例 #28
0
        'application_description':
        '60 шт. ПК от 72-15 до ПК 21-15, Криводановка, с доставкой.',
        'customer_name': 'Алексей',
        'view_number': '12',
    }] * 4,
    'reviews': [{
        'reviewer_name':
        'Кирилл, 29 лет, г. Барабинск',
        'review_text':
        'Бла-бла, мне помогло, все супер! Бла-бла, мне помогло, все супер! Бла-бла, мне помогло, все супер! Бла-бла, мне помогло, все супер! Бла-бла, мне помогло, все супер!',
    }] * 3
}

context_applications = {
    'user_name':
    'Леонид Федорович',
    'applications': [{
        'application_time': 'вчера, в 21:30',
        'application_description':
        '60 шт. ПК от 72-15 до ПК 21-15, Криводановка, с доставкой.',
        'customer_name': 'Алексей',
        'view_number': '12',
    }] * 8
}

if __name__ == "__main__":
    site = make_site(contexts=[('index.html', context_index),
                               ('applications.html', context_applications)],
                     searchpath='templates/')
    site.render()
コード例 #29
0
          decoded = BeautifulSoup(contents)#, smartQuotesTo=None)
          contents = u'\n'.join(map(unicode, decoded.contents))
          contents = contents.encode('ascii', errors='ignore')
          contents = re.sub("\@", "", contents)
        return {'post': contents }


# compilation rule
def render_post(env, template, **kwargs):
    """Render a template as a post."""
    post_template = env.get_template("_post.html")
    head, tail = os.path.split(template.name)
    post_title, _ = tail.split('.')
    if head:
        out = "%s/%s.html" % (head, post_title)
        if not os.path.exists(head):
            os.makedirs(head)
    else:
        out = "%s.html" % (post_title, )
    post_template.stream(**kwargs).dump(out)


if __name__ == "__main__":
    site = make_site(extensions=[
        Markdown2Extension,
    ], contexts=[
        ('.*.md', get_post_contents),
    ], rules=[
        ('.*.md', render_post),
    ])
    site.render(use_reloader=False)
コード例 #30
0
from staticjinja import make_site
import argparse

parser = argparse.ArgumentParser(description='Watch and/or build project')
parser.add_argument('--watch', action='store_true')
args = parser.parse_args()
should_watch = args.watch

if __name__ == "__main__":
    context = {'version': '22'}
    site = make_site(outpath='output',
                     extensions=[
                         'jinja2.ext.with_',
                     ],
                     staticpaths=[
                         'static',
                     ],
                     contexts=[('index.html', context),
                               ('about/index.html', context),
                               ('the-science-behind/index.html', context),
                               ('timeline/index.html', context),
                               ('jp/index.html', context),
                               ('jp/about/index.html', context),
                               ('jp/the-science-behind/index.html', context),
                               ('jp/timeline/index.html', context)])
    site.render(use_reloader=should_watch)
コード例 #31
0
from staticjinja import make_site

context = {
    'number_requisitions_start_page': 4,
    'number_requisitions_per_page': 8,
    'number_suppliers_info_per_page': 6,
    'number_reviews': 2,
    'username': '******',
    'STATIC_URL': 'static/',
}

if __name__ == '__main__':
    site = make_site(
        searchpath='templates',
        outpath='rendered_site',
        staticpaths=['static'],
        contexts=[
            ('.*.html', context),
        ],
    )
    site.render()
コード例 #32
0
ファイル: make_site.py プロジェクト: paganism/22_proto_markup
        'phone': 'Телефон: 00-00-04'
    }, {
        'company': 'ООО Криворукий строитель',
        'working_place': 'Новосибирск',
        'production': 'Продукия: ЖБИ, бетон',
        'address': 'Адрес: Примерно там',
        'phone': 'Телефон: 00-00-02'
    }]
}

company_context = {'username': '******', 'title': 'Об организации'}

profile_context = {'username': '******', 'title': 'Личный кабинет'}

# company_list_context.update(company_list)
company_context.update(company_list_context)
catalog_context.update(company_list_context)
index_context.update(comments_context)
requests_context.update(comments_context)

if __name__ == "__main__":
    site = staticjinja.make_site(outpath='static/',
                                 contexts=[('index.html', index_context),
                                           ('requests.html', requests_context),
                                           ('catalog.html', catalog_context),
                                           ('companies.html', catalog_context),
                                           ('company.html', company_context),
                                           ('profile.html', profile_context)])
    # enable automatic reloading
    site.render()
コード例 #33
0
ファイル: build.py プロジェクト: John2013/22_proto_markup
from staticjinja import make_site

if __name__ == "__main__":
    index = make_site(contexts=[('index.html', {})])

    requests = make_site(contexts=[('requests.html', {
        'show_header_logo':
        True,
        'pages': [
            {
                'number': 1,
                'link': 'javascript:void(0)',
                'is_active': True
            },
            {
                'number': 2,
                'link': 'javascript:void(0)'
            },
            {
                'number': 3,
                'link': 'javascript:void(0)'
            },
            {
                'number': '...',
                'link': 'javascript:void(0)'
            },
            {
                'number': 10,
                'link': 'javascript:void(0)'
            },
        ],
コード例 #34
0
ファイル: __main__.py プロジェクト: steinwurf/ghp-index
def cli(outpath, docspath, project_name, verbose, github_url):

    log = logging.getLogger('ghp_index')

    # Create console handler with a higher log level
    ch = logging.StreamHandler(stream=sys.stdout)
    ch.setLevel(logging.DEBUG if verbose else logging.INFO)
    ch_formatter = logging.Formatter('%(message)s')
    ch.setFormatter(ch_formatter)

    log.addHandler(ch)

    # Expand docs path
    docspath = os.path.abspath(os.path.expanduser(docspath))
    outpath = os.path.abspath(os.path.expanduser(outpath))

    if not os.path.isdir(outpath):
        os.makedirs(outpath)

    log.info("Output path", outpath)
    log.info("Docs path", docspath)

    versions = []

    if docspath and os.path.isdir(docspath):

        for name in os.listdir(docspath):

            dirpath = os.path.join(docspath, name)

            if not os.path.isdir(dirpath):
                continue

            path = os.path.relpath(path=dirpath, start=outpath)

            versions.append((name, path))

    data = {}
    data['versions'] = sorted(versions)
    data['project_name'] = project_name
    data['github_url'] = github_url

    print(versions)

    templates_path = pkg_resources.resource_filename(
        'ghp_index', 'templates')

    assert os.path.isdir(templates_path)

    site = staticjinja.make_site(
        searchpath=templates_path,
        contexts=[
            ('index.html', data)
        ],
        staticpaths=[
            'css',
            'js',
            'images'
        ],
        outpath=outpath)

    site.render()
コード例 #35
0
ファイル: build.py プロジェクト: claudioccm/gant
                category['progress'] = 0
                

                for task in tasks:
                    task['start_date_obj'] = convert_to_time(task['start_date'])
                    task['end_date_obj'] = convert_to_time(task['end_date'])
                    task['months_from_start'] = get_month_delta(start_gantt, task['start_date_obj'])
                    task['left'] = task['months_from_start'] * COL_WIDTH
                    task['timespan'] = (get_month_delta(task['start_date_obj'], task['end_date_obj']) +1) * COL_WIDTH
                    category['progress'] += task['progress']
            
                category['progress'] = category['progress'] / len(tasks)
                stage['progress'] += category['progress']

            stage['progress'] = stage['progress'] / len(categories)

    return ctx

if __name__ == '__main__':
    site = make_site(
        filters={},
        outpath=_OUTPUTPATH,
        contexts=[(r'.*.html', enhance_data)],
        searchpath=_SEARCHPATH,
        staticpaths=['static', '../data']
    )

    # cleanup()

    site.render(use_reloader=True)
コード例 #36
0
ファイル: build.py プロジェクト: JSGS867/www.thegovlab.org
    Deploy the site to production.
    '''

    subprocess.check_call('git subtree push --prefix site origin gh-pages',
                          shell=True)


if __name__ == '__main__':
    context = ReloadingContext()

    site = staticjinja.make_site(filters=filters(),
                                 outpath=_OUTPUTPATH,
                                 contexts=[
                                     (r'.*.html', context.get),
                                     (r'project-detail-pages.custom',
                                      context.get),
                                 ],
                                 rules=[(r'project-detail-pages.custom',
                                         render_project_detail_pages)],
                                 searchpath=_SEARCHPATH,
                                 staticpaths=['static'])

    manager = Manager(
        sass_src_path=path.join(_SASSPATH, 'styles.scss'),
        sass_dest_path=path.join(_SEARCHPATH, 'static', 'styles',
                                 'styles.css'),
        site=site,
        site_name='www.thegovlab.org',
    )
    context.add_to(manager)
    argh.add_commands(manager.parser, [deploy, clean])
コード例 #37
0
ファイル: build.py プロジェクト: eMedranoPicon/prueba
from staticjinja import make_site
from jinja2 import Environment
import context_vars.context_list as context

if __name__ == "__main__":

    renderer = make_site(searchpath='./app/templates',
                         outpath="./app/dist",
                         contexts=context.get_context_list(),
                         extensions=['jinja2.ext.with_'])
    renderer.render()

#     import staticjinja
# import os
# import contextVars.context_list as context

# if __name__ == "__main__":
#     searchpath = "./app/templates/"
#     outpath = "./app/dist/plantillas/site-mi-residencia/"
#     dir = os.path.dirname(outpath)

#     if not os.path.exists(dir):
#         os.makedirs(dir)

# renderer = staticjinja.make_renderer(searchpath=searchpath, outpath=outpath, contexts=context.get_context_list())
# renderer.run()
コード例 #38
0
ファイル: build.py プロジェクト: toolness/noi-ui
for filename in listdir(searchpath):
    filepath = '%s/%s' % (searchpath, filename)

    if filename.startswith('article-') and path.isfile(filepath):
        remove(filepath)

# Clean the output folder.
if path.exists(outputpath):
    rmtree(outputpath)

makedirs(outputpath)

# CREATES A MULTIPLE PAGE GENERATOR, BASED IN THE 'article.html' TEMPLATE
# for index, data in enumerate(DATA):
#     filename = slugify(data['title'].lower())
#     new_file = open('%s/article-%s.html' % (searchpath, filename), 'w+')
#     new_page = template.replace('data[0]', 'data[%d]' % index)

#     new_file.write(new_page)
#     new_file.close()

site = make_site(
    filters={},
    outpath=outputpath,
    contexts=[(r'.*.html', loadData)],
    searchpath=searchpath,
    staticpaths=['static', '../data']
)

site.render(use_reloader=True)
コード例 #39
0
ファイル: build.py プロジェクト: nweinthal/jaytwo
from staticjinja import make_site


if __name__ == "__main__":
    site = make_site()
    # enable automatic reloading
    site.render(use_reloader=True)
コード例 #40
0
import staticjinja
import os

url = 'http://localhost:8000'

if os.environ.get('PYCON_ENV') == 'PROD':
    url = 'https://pune.pycon.org/2017'

if __name__ == "__main__":
    site = staticjinja.make_site(contexts=[('.*.html', {'url': url})], )
    site.render(use_reloader=True)
コード例 #41
0
ファイル: build.py プロジェクト: cbouilla/3sum-pool
from staticjinja import make_site

context = {"webservice": "52.5.252.107"}

site = make_site(contexts=[('.*', context)],
                 outpath="output/",
                 searchpath="templates",
                 staticpaths=["images/", "fonts/", "css/", "static_js/"])
site.render()
コード例 #42
0
def watch_templates():
    print('Monitoring templates...')

    site = make_site(outpath="dist")
    site.render(use_reloader=True)
コード例 #43
0
                    required=True)

args = vars(parser.parse_args())


def get_attendee_data():
    import csv
    with open('workshop.csv') as csvfile:
        pycon_india_worskhops = csv.reader(csvfile)
        attendee_id = int(args["id"])
        attendees = []
        for linenumber, row in enumerate(pycon_india_worskhops):
            if linenumber >= attendee_id:
                if linenumber > attendee_id + 15:
                    break
                attendee = {'name': str(row[0]).title(), 'id': linenumber}
                # attendee = {'name': str(row[0]).title(), 'id': 1}
                attendees.append(attendee)
        print(len(attendees))
        return attendees[0:][::2], attendees[1:][::2]


if __name__ == "__main__":
    attendees_group_1, attendees_group_2 = get_attendee_data()
    site = make_site(contexts=[('index.html', {
        "attendees_group_1": attendees_group_1,
        "attendees_group_2": attendees_group_2
    })])
    # enable automatic reloading
    site.render(use_reloader=True)
コード例 #44
0
from staticjinja import make_site
import time

if __name__ == "__main__":
    context_home = {"navbar_class": "navbar-home"}
    contexts = [
        ('index.html', context_home),
    ]
    while (1):
        site = make_site(contexts=contexts)
        site.render()
        site.render(use_reloader=True)
コード例 #45
0
ファイル: build.py プロジェクト: becmcr/govlab-website
        new_file.write(new_page)
        new_file.close()


if __name__ == '__main__':
    auto = _AUTO_RELOAD
    ctxt = context()
    site = {}

    cleanup()
    create_custom_templates(ctxt['projects'])

    # Accept CLI parameter to turn the auto reloader on and off.
    if len(argv) == 2:
        arg = argv[1].lower()

        if arg in ['0', 'false', 'off', 'no']:
            auto = False

        elif arg in ['1', 'true', 'on', 'yes']:
            auto = True

    site['filters'] = filters()
    site['outpath'] = _OUTPUTPATH
    site['contexts'] = [(r'.*.html', lambda: ctxt)]
    site['searchpath'] = _SEARCHPATH
    site['staticpaths'] = ['static']

    make_site(**site).render(use_reloader=auto)
コード例 #46
0
                             type=int,
                             help='''Web-server port. Default: 8000.''')
    httpd_group.add_argument("-b",
                             "--bind",
                             dest="bind",
                             default='',
                             help='''Web-server bind address.''')
    parser.add_argument("command",
                        default="build",
                        choices=["build", "host"],
                        nargs='?')

    args = parser.parse_args()

    site = make_site(searchpath=os.path.abspath(args.searchpath),
                     outpath=os.path.abspath(args.output),
                     staticpaths=args.staticpath)
    do_host = (args.command == "host")
    if not do_host:
        site.render(use_reloader=False)
    else:
        os.chdir(os.path.abspath(args.output))
        server_address = (args.bind, args.port)
        with HTTPServer(server_address=server_address,
                        RequestHandlerClass=SimpleHTTPRequestHandler) as httpd:
            sa = httpd.socket.getsockname()
            serve_message = "Serving HTTP on {host} port {port} (http://{host}:{port}/) ..."
            print(serve_message.format(host="127.0.0.1", port=sa[1]))
            thread = Thread(target=httpd.serve_forever)
            thread.daemon = True
            thread.start()
コード例 #47
0
            contents = contents.encode('ascii', errors='ignore')
            contents = re.sub("\@", "", contents)
        return {'post': contents}


# compilation rule
def render_post(env, template, **kwargs):
    """Render a template as a post."""
    post_template = env.get_template("_post.html")
    head, tail = os.path.split(template.name)
    post_title, _ = tail.split('.')
    if head:
        out = "%s/%s.html" % (head, post_title)
        if not os.path.exists(head):
            os.makedirs(head)
    else:
        out = "%s.html" % (post_title, )
    post_template.stream(**kwargs).dump(out)


if __name__ == "__main__":
    site = make_site(extensions=[
        Markdown2Extension,
    ],
                     contexts=[
                         ('.*.md', get_post_contents),
                     ],
                     rules=[
                         ('.*.md', render_post),
                     ])
    site.render(use_reloader=False)
コード例 #48
0
ファイル: __main__.py プロジェクト: Ceasar/staticjinja
#!/usr/bin/env python
# -*- coding:utf-8 -*-

from __future__ import absolute_import

import os

import staticjinja

if __name__ == "__main__":
    searchpath = os.path.join(os.getcwd(), 'templates')
    site = staticjinja.make_site(searchpath=searchpath)
    site.render(use_reloader=True)
コード例 #49
0
from staticjinja import make_site
import context_vars.context_list as context

if __name__ == "__main__":

    renderer = make_site(searchpath='./app/templates',
                         outpath="./app/dist",
                         contexts=context.get_context_list())
    renderer.render()
コード例 #50
0
ファイル: build.py プロジェクト: Texas-UCF/options-curriculum
          ('Moneyness', 'moneyness.html'),
          ('Downside vs Upside', 'down_upside.html'),
          ('Cost of Options', 'options_cost.html'),
        ]
      )
    ),
    ('Profit Diagrams', od(
        [
          ('Payoff', 'payoff_diagram.html'),
          ('Profit at Expiration', 'profit_at_expiration.html'),
        ]
      )
    )
    ]
  )
  return {'sections': sections}

def get_contents(template):
  with open(template.filename) as f:
    return {'page': f.read()}

if __name__ == '__main__':
  site = make_site(
      contexts=[
        ('.*.html', get_sections),
      ],
      outpath="site",
      staticpaths=['static'],
    )

  site.render(use_reloader=True)