Example #1
0
 def test_preserve_blocks(self):
     env = Environment(loader=DictLoader({
         'a': '{% if false %}{% block x %}A{% endblock %}{% endif %}{{ self.x() }}',
         'b': '{% extends "a" %}{% block x %}B{{ super() }}{% endblock %}'
     }))
     tmpl = env.get_template('b')
     assert tmpl.render() == 'BA'
Example #2
0
def _get_environment():
    """Get the Jinja2 environment

    :returns: the jinja2 environment
    """
    global environment
    if environment is None:
        import jip
        cfg = jip.config.templates
        # global environment
        environment = Environment(undefined=JipUndefined,
                                  variable_start_string=cfg.get(
                                      'variable_open',
                                      '${'
                                  ),
                                  variable_end_string=cfg.get(
                                      'variable_close',
                                      '}'
                                  ))
        environment.filters['arg'] = arg_filter
        environment.filters['else'] = else_filter
        environment.filters['name'] = name_filter
        environment.filters['ext'] = ext_filter
        environment.filters['abs'] = abs_filter
        environment.filters['suf'] = suf_filter
        environment.filters['pre'] = pre_filter
        environment.filters['parent'] = parent_filter
        environment.filters['re'] = replace_filter
    return environment
Example #3
0
def render_tmplt(path, cp):
    """ Render a file as text.
    """

    # define filename and slug from path
    filename = os.path.basename(path)
    slug = filename.replace('.', '_')

    # initializations
    content = None

    # read file as a string
    with open(path, 'rb') as fp:
        content = fp.read()

    # replace all the escaped characters
    content = unescape(content, unescape_table)

    # render template
    template_dir = '/'.join(path.split('/')[:-1])
    env = Environment(loader=FileSystemLoader(template_dir))
    env.globals.update(setup_template_render=setup_template_render)
    env.globals.update(get_embedded_config=get_embedded_config)
    env.globals.update(path_exists=os.path.exists)
    template = env.get_template(filename)
    context = {'filename' : filename,
               'slug'     : slug,
               'cp'       : cp,
               'content'  : content}
    output = template.render(context)

    return output
Example #4
0
    def test_nested_structures(self):
        env = Environment(extensions=[SerializerExtension])
        rendered = env.from_string('{{ data }}').render(data="foo")
        self.assertEqual(rendered, u"foo")

        data = OrderedDict([
            ('foo', OrderedDict([
                        ('bar', 'baz'),
                        ('qux', 42)
                    ])
            )
        ])

        rendered = env.from_string('{{ data }}').render(data=data)
        self.assertEqual(rendered, u"{'foo': {'bar': 'baz', 'qux': 42}}")

        rendered = env.from_string('{{ data }}').render(data=[
                                                            OrderedDict(
                                                                foo='bar',
                                                            ),
                                                            OrderedDict(
                                                                baz=42,
                                                            )
                                                        ])
        self.assertEqual(rendered, u"[{'foo': 'bar'}, {'baz': 42}]")
Example #5
0
def make_exercise(src, tgt):
    problems = []
    exercise = json.load(open(src))
    problems = []
    for problem in expand_problems(exercise.pop('problems')):
        problem['query'] = query = " ".join([problem['instruction'], problem['latex']])
        problem['exid'] = exid = "SYMB_" + hashlib.md5(query).hexdigest().upper()[:7]
        solution = get_solution(query)

        for k in "computesTo debugInfo".split():
            solution.pop(k, None)
        problem['solution'] = solution.pop('solutions')[0]
        problem.setdefault('title', exercise['default_problem_title'])
        problem.setdefault('latex_buttons', exercise['latex_buttons'])
        problems.append(problem)
    exercise['problems'] = problems

    from jinja2 import Environment, FileSystemLoader
    env = Environment(trim_blocks=True, lstrip_blocks=True, loader=FileSystemLoader(BASE_PATH))
    env.filters.update(latex=latex, direction=direction)

    template_name = exercise.get("template", "template.html")
    template = env.get_template(template_name)
    html = template.render(exercise=exercise)
    if obfuscate:
        html = "".join(html.splitlines())

    with open(tgt, "w") as f:
        print("Writing %s" % tgt)
        print(html.encode("utf8"), file=f)

    for problem in problems:
        print('%(host)s/exercises/%(url)s?problem=%(exid)s\n\t%(query)s\n' % dict(problem, host=LOCAL_HOST, url=basename(tgt)))

    print("- Done (%s problems)" % len(problems))
Example #6
0
 def generate_html(self):
     self.set_baselineinfo()
     self.analyze_result()
     self.copy_template()
     env = Environment(loader=PackageLoader('ChorusCore', 'templates'))
     for suite_name, suiteresult in self.result.suites.iteritems():
         suitetemplate = env.get_template("suite.html")
         content = suitetemplate.render({"result":suiteresult.__dict__, "bsinfo":self.updateinfo})
         filename = os.path.join(self.output_path, '%s.html' % suite_name )
         Utils.write_to_file(filename, content, "w+")
         self.logger.info("Suite %s.html generated" % suite_name)
     summarytemplate = env.get_template('summary.html')
     xmltemplate = env.get_template('summary.xml')
     content = summarytemplate.render({"result":self.result,"ea":Performance_Result})
     filename = os.path.join(self.output_path, 'Summary.html')
     Utils.write_to_file(filename, content, "w+")
     self.logger.info("Summary.html generated")
     #TODO Modify xml
     content = xmltemplate.render({"result":self.result})
     filename = os.path.join(self.output_path, 'Summary.xml')
     Utils.write_to_file(filename, content, "w+")
     self.logger.info("Summary.xml generated")
     if os.environ.has_key("BUILD_URL"):
         self.generate_result_email()
     if Performance_Result.data:
         self.generate_performance_result()
Example #7
0
def render(db):
    env = Environment(loader=FileSystemLoader(template_dir))
    env.filters['toUrl'] = toUrl

    # Copy resources
    shutil.copytree(template_dir + 'assets', destination_dir + 'assets')
    shutil.copytree('build/avatars', destination_dir + 'avatars')

    # Profile pages
    councillors = db['councillors']

    votes_mapping = db['votes'].find()
    votes_mapping = {curr["_id"]: curr for curr in votes_mapping}
    # for m in votes_mapping:
    #     print(m)
    # print(votes_mapping)

    for councillor in councillors.find():
        name = 'grossraete/{0}/index'.format(toUrl(councillor['fullname']))
        render_page(env, 'councillor_details', name,
                    councillor=councillor, votes_mapping=votes_mapping,
                    title=councillor['fullname'])

    # Index pages
    render_page(env, 'councillor_index', 'grossraete/index',
                     db=db, councillors=councillors.find(), title='Grossräte')

    #  Base for comparison
    render_page(env, 'compare', 'vergleichen/index')
    def _create_environment(self):
        """
        Create the Jinja templating environment.
        """
        from jinja2 import Environment, ChoiceLoader, FileSystemLoader
        here = os.path.dirname(os.path.realpath(__file__))

        paths = self.template_path + \
            [os.path.join(here, self.default_template_path),
             os.path.join(here, self.template_skeleton_path)]

        loaders = self.extra_loaders + [FileSystemLoader(paths)]
        environment = Environment(
            loader= ChoiceLoader(loaders),
            extensions=JINJA_EXTENSIONS
            )

        environment.globals['uuid4'] = uuid.uuid4

        # Add default filters to the Jinja2 environment
        for key, value in self.default_filters():
            self._register_filter(environment, key, value)

        # Load user filters.  Overwrite existing filters if need be.
        if self.filters:
            for key, user_filter in self.filters.items():
                self._register_filter(environment, key, user_filter)

        return environment
class RenderTestCase(TestCase):

    templates_path = os.path.join(os.path.dirname(os.getcwd()), u'templates')

    def setUp(self):
        self.env = Environment(loader=FileSystemLoader(self.templates_path))

    def test_simple_list(self):
        dut = Element(u'ul', u'text', {u'class': u'some class'})
        dut.child.append(Element(u'li', u'text', {u'class': u'some class'}))
        dut.child.append(Element(u'li', u'text', {u'class': u'some class'}))

        result = self.env.get_template(u'json2html.html').render(root=dut.render())

        expect = u'<ul class="some class">text<li class="some class">text</li><li class="some class">text</li></ul>'

        self.assertEqual(result, expect)

    def test_property(self):
        dut = Element(u'ul', u'text', {u'class': u'some class'})
        dut.child.append(Element(u'li', u'text', {u'disable': None}))
        dut.child.append(Element(u'li', u'text', {u'disable': u''}))

        result = self.env.get_template(u'json2html.html').render(root=dut.render())

        expect = u'<ul class="some class">text<li disable>text</li><li disable>text</li></ul>'

        self.assertEqual(result, expect)
Example #10
0
    def test_stacked_locals_scoping_bug(self):
        env = Environment(line_statement_prefix="#")
        t = env.from_string(
            """\
# for j in [1, 2]:
#   set x = 1
#   for i in [1, 2]:
#     print x
#     if i % 2 == 0:
#       set x = x + 1
#     endif
#   endfor
# endfor
# if a
#   print 'A'
# elif b
#   print 'B'
# elif c == d
#   print 'C'
# else
#   print 'D'
# endif
    """
        )
        assert t.render(a=0, b=False, c=42, d=42.0) == "1111C"
Example #11
0
def main():
    """ Get hardware info, format it, and write to slurm.conf and gres.conf """
    args = parse_args()

    # Get info from cnode and xthwinv
    repurposed = get_repurposed_computes(args.partition)
    nodes = get_inventory(args.partition, repurposed)
    nodelist = rli_compress([int(nid) for nid in nodes])
    compact_nodes(nodes)
    defmem, maxmem = get_mem_per_cpu(nodes)

    # Write files from templates
    jinjaenv = Environment(loader=FileSystemLoader(args.templatedir))
    conffile = os.path.join(args.output, 'slurm.conf')
    print 'Writing Slurm configuration to {0}...'.format(conffile)
    with open(conffile, 'w') as outfile:
        outfile.write(jinjaenv.get_template('slurm.conf.j2').render(
            script=sys.argv[0],
            date=time.asctime(),
            controlmachine=args.controlmachine,
            grestypes=get_gres_types(nodes),
            defmem=defmem,
            maxmem=maxmem,
            nodes=nodes,
            nodelist=nodelist))

    gresfilename = os.path.join(args.output, 'gres.conf')
    print 'Writing gres configuration to {0}...'.format(gresfilename)
    with open(gresfilename, 'w') as gresfile:
        gresfile.write(jinjaenv.get_template('gres.conf.j2').render(
            script=sys.argv[0],
            date=time.asctime(),
            nodes=nodes))

    print 'Done.'
Example #12
0
    def to_html(self):
        from jinja2 import Environment, FileSystemLoader
        env = Environment(loader=FileSystemLoader('%s/templates' % (os.path.dirname(os.path.abspath(__file__)),)))
        template = env.get_template('sql_table.html')
        html = template.render({"header": self.theader_list, "body": self.data})

        return html
Example #13
0
class Builder:
    def __init__(self, out_file):
        self.env = Environment(loader=PackageLoader('builder', 'templates'))
        self.out_file = out_file

        # provides a template helper to turn a list into a list of pairs
        self.env.filters['pairs'] = lambda l: [l[i:i + 2] for i in range(0, len(l), 2)]

    # inlines css using premailer with my specific configuration, namely, must
    # keep classes so responsiveness can work.
    def premailer(self, html):
        return Premailer(html, base_url=None, remove_classes=False).transform()

    # creates a string of rendered html
    def render(self, elements):
        body = ''

        # loop through given elements and render respective template with options
        for element in elements:
            template = self.env.get_template(element['template'])   # gets the template
            body += template.render(element['options'])             # renders the template

        layout = self.env.get_template('body.html')     # get layout template
        output = layout.render(body=body)               # render into layout
        return self.premailer(output)

    # writes the rendered string to the specified file
    def write(self, elements):
        output = self.render(elements)          # builds the html string
        with open(self.out_file, "w") as html:  # writes the html to a file
            html.write(output)
Example #14
0
def fill_template(player_data, lang, fundamental, yaku):
    """Build long text which shows the statistics of the target
    player(s).
    """

    target_games = player_data[0]['games'] if player_data else None
    if not target_games:
        return 'NO DATA\n'

    env = Environment(autoescape=False)
    env.filters.update(
        format_float=format_float,
        format_percentage=format_percentage,)

    output_text = env.from_string(lang.tmpl_summary).render(
        count_games=len(target_games),
        started_at=target_games[0]['started_at'],
        finished_at=target_games[-1]['finished_at'],
        data=player_data)

    if fundamental:
        output_text += env.from_string(lang.tmpl_fundamental).render(
            data=player_data)

    if yaku:
        yaku_name_map = {y:lang.yaku_names[i]
                         for i, y in enumerate(YakuTable)}
        output_text += env.from_string(lang.tmpl_yaku_freq).render(
            data=player_data,
            YakuTable=YakuTable,
            yaku_name_map=yaku_name_map)

    return output_text
Example #15
0
def init_jinja2(app, **kw):
    logging.info("init jinja2...")
    # 初始化模板配置,包括模板运行代码的开始结束标识符,变量的开始结束标识符等
    options = dict(
        # 是否转义设置为True,就是在渲染模板时自动把变量中的<>&等字符转换为&lt;&gt;&amp;        
        autoescape = kw.get("autoescape", True),     # 自动转义xml/html的特殊字符
        block_start_string = kw.get("block_start_string", "{%"), # 代码块开始标志
        block_end_string = kw.get("block_end_string", "%}"),     # 代码块结束标志
        variable_start_string = kw.get("variable_start_string", "{{"), # 变量开始标志
        variable_end_string = kw.get("variable_end_string", "}}"),     # 变量结束标志
        # Jinja2会在使用Template时检查模板文件的状态,如果模板有修改, 则重新加载模板。如果对性能要求较高,可以将此值设为False
        auto_reload = kw.get("auto_reload", True) # 每当对模板发起请求,加载器首先检查模板是否发生改变.若是,则重载模板
        )
    # 从参数中获取path字段,即模板文件的位置
    path = kw.get("path", None) 
    if path is None:
        # 若路径不存在,则默认为当前文件目录下的 templates 目录
        # os.path.abspath(__file__), 返回当前脚本的绝对路径(包括文件名)
        # os.path.dirname(), 去掉文件名,返回目录路径
        # os.path.join(), 将分离的各部分组合成一个路径名
        path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "templates")
    logging.info("set jinja2 template path: %s" % path)
    # Environment是Jinja2中的一个核心类,它的实例用来保存配置、全局对象,以及从本地文件系统或其它位置加载模板。
    # 这里把要加载的模板和配置传给Environment,生成Environment实例
    # 加载器负责从指定位置加载模板, 此处选择FileSystemLoader,顾名思义就是从文件系统加载模板,前面我们已经设置了path
    env = Environment(loader = FileSystemLoader(path), **options)
    # 从参数取filter字段
    # filters: 一个字典描述的filters过滤器集合, 如果非模板被加载的时候, 可以安全的添加filters或移除较早的.
    filters = kw.get("filters", None)
    # 如果有传入的过滤器设置,则设置为env的过滤器集合
    if filters is not None:
        for name, f in filters.items():
            env.filters[name] = f
    # 给webapp设置模板
    app["__templating__"] = env
Example #16
0
class Jinja2Template(BaseTemplate):
    env = None # hopefully, a Jinja environment is actually thread-safe

    def prepare(self):
        if not self.env:
            from jinja2 import Environment, FunctionLoader
            self.env = Environment(line_statement_prefix="#", loader=FunctionLoader(self.loader))
        if self.template:
            self.tpl = self.env.from_string(self.template)
        else:
            self.tpl = self.env.get_template(self.filename)

    def render(self, **args):
        return self.tpl.render(**args).encode("utf-8")
        
    def loader(self, name):
        if not name.endswith(".tpl"):
            for path in self.lookup:
                fpath = os.path.join(path, name+'.tpl')
                if os.path.isfile(fpath):
                    name = fpath
                    break
        f = open(name)
        try: return f.read()
        finally: f.close()
Example #17
0
def render_all(template_path=None, output_path=None):
    if not template_path:
        template_path = os.getcwd() + '/templates'
    if not output_path:
        output_path = os.getcwd() + '/rendered_website'
    env = Environment(loader=MyLoader(template_path))
    # find all the files inside all the subdirectories of the template path
    all_the_things = os.walk(template_path)
    for root, dirs, files in all_the_things:
        for f in files:
            # check that it's a template file
            if f[-5:] == '.html' and f[:1] != '_':
                full_path = root + '/' + f
                # path relative to template_path
                relative_path = full_path[len(template_path) + 1:]
                print "Rendering " + relative_path
                # render the template
                template = env.get_template(relative_path)
                # calculate directory output should go in
                dirname = os.path.dirname(output_path + '/' + relative_path)
                # and if it doesn't exist yet, create it
                if not os.path.exists(dirname):
                    os.makedirs(dirname)
                # make rendered html file
                with codecs.open(output_path + '/' + relative_path, 'w', 'utf-8') as render_file:
                    for line in template.render():
                        render_file.write(line)
Example #18
0
def warning(message):
    """Print a warning message on the rich text view"""

    env = Environment()
    env.loader = FileSystemLoader(osp.join(CONFDIR_PATH, 'templates'))
    warning = env.get_template("warning.html")
    return warning.render(css_path=CSS_PATH, text=message)
Example #19
0
def build(outfile, template, content_file):
    content = Content(content_file)
    template_dir, template_file = os.path.split(template)
    output_dir, output_file = os.path.split(outfile)
    env = Environment(
        block_start_string="%{",
        block_end_string="%}",
        variable_start_string="%{{",
        variable_end_string="%}}",
        comment_start_string="%{#",
        comment_end_string="%#}",
        line_comment_prefix="%#",
        line_statement_prefix="%##",
        loader=FileSystemLoader(template_dir),
    )
    template = env.get_template(template_file)
    with codecs.open(outfile, "wb", encoding="utf-8") as f:
        f.write(
            template.render(
                last_updated=format_date(),
                git_hash=content.get_git_hash(),
                schools=content.get_schools(),
                experience=content.get_experience(),
                skills=content.get_skills(),
                languages=content.get_languages(),
            )
        )
    os.system('lualatex -shell-escape --output-directory="' + output_dir + '" ' + outfile)
Example #20
0
 def test_filesystem_loader(self):
     env = Environment(loader=filesystem_loader)
     tmpl = env.get_template('test.html')
     assert tmpl.render().strip() == 'BAR'
     tmpl = env.get_template('foo/test.html')
     assert tmpl.render().strip() == 'FOO'
     self.assert_raises(TemplateNotFound, env.get_template, 'missing.html')
Example #21
0
 def test_volatile(self):
     env = Environment(extensions=['jinja2.ext.autoescape'],
                       autoescape=True)
     tmpl = env.from_string('{% autoescape foo %}{{ {"foo": "<test>"}'
                            '|xmlattr|escape }}{% endautoescape %}')
     assert tmpl.render(foo=False) == ' foo=&#34;&amp;lt;test&amp;gt;&#34;'
     assert tmpl.render(foo=True) == ' foo="&lt;test&gt;"'
Example #22
0
 def test_choice_loader(self):
     env = Environment(loader=choice_loader)
     tmpl = env.get_template('justdict.html')
     assert tmpl.render().strip() == 'FOO'
     tmpl = env.get_template('test.html')
     assert tmpl.render().strip() == 'BAR'
     self.assert_raises(TemplateNotFound, env.get_template, 'missing.html')
Example #23
0
def init_jinja2(app, **kw):
	logging.info('init jinja2...')
	#初始化模板配置,包括模板运行代码的开始结束标识符,变量的开始结束标识符等
	options = dict(
		autoescape = kw.get('autoescape', True),	#是否转义设置为True,就是在渲染模板时自动把变量中的<>&等字符转换为&lt;&gt;&amp;
		block_start_string = kw.get('block_start_string', '{%'),	#运行代码的开始标识符
		block_end_string = kw.get('block_end_string', '%}'),		#运行代码的结束标识符
		variable_start_string = kw.get('variable_start_string', '{{'),	#变量开始标识符
		variable_end_string = kw.get('variable_end_string', '}}'),		#变量结束标识符
		auto_reload = kw.get('auto_reload', True)	#Jinja2会在使用Template时检查模板文件的状态,如果模板有修改, 则重新加载模板。如果对性能要求较高,可以将此值设为False
	)
	#从参数中获取path字段,即模板文件的位置
	path = kw.get('path', None)
	#如果没有,则默认为当前文件目录下的 templates 目录
	if path is None:
		path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'templates')
	logging.info('set jinja2 template path: %s' % path)
	#Environment是Jinja2中的一个核心类,它的实例用来保存配置、全局对象,以及从本地文件系统或其它位置加载模板。
	#这里把要加载的模板和配置传给Environment,生成Environment实例
	env = Environment(loader=FileSystemLoader(path), **options)
	#从参数取filter字段
	# filters: 一个字典描述的filters过滤器集合, 如果非模板被加载的时候, 可以安全的添加filters或移除较早的.
	filters = kw.get('filters', None)
	#如果有传入的过滤器设置,则设置为env的过滤器集合
	if filters is not None:
		for name, f in filters.items():
			env.filters[name] = f
	#给webapp设置模板
	app['__templating__'] = env
Example #24
0
 def test_prefix_loader(self):
     env = Environment(loader=prefix_loader)
     tmpl = env.get_template('a/test.html')
     assert tmpl.render().strip() == 'BAR'
     tmpl = env.get_template('b/justdict.html')
     assert tmpl.render().strip() == 'FOO'
     self.assert_raises(TemplateNotFound, env.get_template, 'missing')
def render_all(template_path=None, output_path=None, static_path=None):
    if not template_path:
        template_path = 'lae_site/templates/'
    if not output_path:
        output_path = 'lae_rendered/'
    if not static_path:
        static_path = 'content/static/'
    env = Environment(loader=MyLoader(template_path))
    # find all the files inside all the subdirectories of the template path
    all_the_things = os.walk(template_path)
    for root, dirs, files in all_the_things:
        for f in files:
            # check that it's a template file
            if f[-5:] == '.html' and f[:1] != '_':
                full_path = root + '/' + f
                # path relative to template_path
                relative_path = full_path[len(template_path) + 1:]
                print "Rendering " + relative_path
                # render the template
                template = env.get_template(relative_path)
                # calculate directory output should go in
                dirname = os.path.dirname(output_path + '/' + relative_path)
                # and if it doesn't exist yet, create it
                if not os.path.exists(dirname):
                    os.makedirs(dirname)
                # make rendered html file
                with codecs.open(output_path + '/' + relative_path, 'w', 'utf-8') as render_file:
                    for line in template.render():
                        render_file.write(line)
    if not os.path.isdir(output_path + 'static'):
        subprocess.check_call(['ln', '-s', '../' + static_path, 'static'], cwd=os.getcwd() + '/' + output_path)
    print "Made symlink to static files."
    subprocess.check_call(['python', '-m', 'SimpleHTTPServer', '8002'], cwd=os.getcwd() + '/' + output_path)
Example #26
0
def execute_programmatically(uid, pipeline, output_dir, notebook=None, script=None, **args):
    if isinstance(uid, str):
        # force it to look like a string in the templated notebook
        uid = "'{}'".format(uid)
    if notebook:
        template_dir = notebooks_path
        suffix = '.ipynb'
    elif script:
        template_dir = scripts_path
        suffix = '.py'
    else:
        raise ValueError("You must supply `notebook` or `script` as a kwarg")

    logger.info("Template directory = %s" % template_dir)
    jinja_env = Environment(loader=FileSystemLoader(template_dir))

    output_path = os.path.join(output_dir, pipeline+suffix)
    logger.info("Writing to %s" % output_path)

    template_name = '%s.tmpl' % pipeline
    logger.info("Loading template = %s" % template_name)

    template = jinja_env.get_template(template_name)
    template_info = {'uid': uid}
    pipeline = template.render(**template_info)
    with open(output_path, 'w') as f:
        f.write(pipeline)
Example #27
0
def render_text(path, cp):
    """ Render a file as text.
    """

    # define filename and slug from path
    filename = os.path.basename(path)
    slug = filename.replace('.', '_')

    # initializations
    content = None

    # read file as a string
    with codecs.open(path, 'r', encoding='utf-8', errors='replace') as fp:
        content = fp.read()

    # replace all the escaped characters
    content = unescape(content, unescape_table)

    # render template
    template_dir = pycbc.results.__path__[0] + '/templates/files'
    env = Environment(loader=FileSystemLoader(template_dir))
    env.globals.update(abs=abs)
    env.globals.update(path_exists=os.path.exists)
    template = env.get_template('file_pre.html')
    context = {'filename' : filename,
               'slug'     : slug,
               'cp'       : cp,
               'content'  : content}
    output = template.render(context)

    return output
Example #28
0
class jinja2_renderer_factory(object):
    def __init__(self, search_paths=(), default_templates='deform_jinja2:templates',
            translator=None, extensions=[]):

        if 'jinja2.ext.i18n' not in extensions:
           extensions.append('jinja2.ext.i18n')

        self.env = Environment(extensions=extensions)
        self.env.loader = FileSystemLoader(())

        for path in search_paths:
            self.add_search_path(path)

        if translator == None:
            translator = DummyTranslator

        self.env.install_gettext_callables(translator.gettext, translator.ngettext)

        self.add_search_path(default_templates)

    def add_search_path(self, path):
        self.env.loader.searchpath.append(resource_filename(*(path.split(':'))))

    def add_filter(self, name, func):
        self.env.filters[name] = func

    def __call__(self, tname, **kw):
        if not '.jinja2' in tname:
            tname += '.jinja2'

        template = self.env.get_template(tname)
        return template.render(**kw)
Example #29
0
def render_workflow_html_template(filename, subtemplate, filelists, **kwargs):
    """ Writes a template given inputs from the workflow generator. Takes
    a list of tuples. Each tuple is a pycbc File object. Also the name of the
    subtemplate to render and the filename of the output.
    """

    dirnam = os.path.dirname(filename)
    makedir(dirnam)

    try:
        filenames = [f.name for filelist in filelists for f in filelist if f is not None]
    except TypeError:
        filenames = []

    # render subtemplate
    subtemplate_dir = pycbc.results.__path__[0] + '/templates/wells'
    env = Environment(loader=FileSystemLoader(subtemplate_dir))
    env.globals.update(get_embedded_config=get_embedded_config)
    env.globals.update(path_exists=os.path.exists)
    env.globals.update(len=len)
    subtemplate = env.get_template(subtemplate)
    context = {'filelists' : filelists,
               'dir' : dirnam}
    context.update(kwargs)
    output = subtemplate.render(context)

    # save as html page
    kwds = {'render-function' : 'render_tmplt',
            'filenames' : ','.join(filenames)}
    save_html_with_metadata(str(output), filename, None, kwds)
Example #30
0
    def output_blob(self):
        """Output to the template after all messages."""
        if self.current_file_linted is None:
            # There were no files checked.
            print('[ERROR]: No files were checked.')
            return

        template_f = self.linter.config.pyta_template_file
        template = Environment(loader=FileSystemLoader(TEMPLATES_DIR)).get_template(template_f)

        # Embed resources so the output html can go anywhere, independent of assets.
        # with open(os.path.join(TEMPLATES_DIR, 'pyta_logo_markdown.png'), 'rb+') as image_file:
        #     # Encode img binary to base64 (+33% size), decode to remove the "b'"
        #     pyta_logo_base64_encoded = b64encode(image_file.read()).decode()

        # Date/time (24 hour time) format:
        # Generated: ShortDay. ShortMonth. PaddedDay LongYear, Hour:Min:Sec
        dt = str(datetime.now().strftime('%a. %b. %d %Y, %I:%M:%S %p'))
        output_path = os.path.join(os.getcwd(), self.linter.config.pyta_output_file)
        with open(output_path, 'w') as f:
            f.write(template.render(date_time=dt,
                                    # pyta_logo=pyta_logo_base64_encoded,
                                    reporter=self))
        print('Opening your report in a browser...')
        output_url = 'file:///{}'.format(output_path)
        webbrowser.open(output_url, new=2)