Beispiel #1
0
 def test_prefix_loader(self, prefix_loader):
     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"
     pytest.raises(TemplateNotFound, env.get_template, "missing")
Beispiel #2
0
 def test_cache_loader_change(self):
     loader1 = loaders.DictLoader({"foo": "one"})
     loader2 = loaders.DictLoader({"foo": "two"})
     env = Environment(loader=loader1, cache_size=2)
     assert env.get_template("foo").render() == "one"
     env.loader = loader2
     assert env.get_template("foo").render() == "two"
Beispiel #3
0
    def test_scopes_and_blocks(self):
        env = Environment(
            loader=DictLoader({
                "a.html": """
                {%- set foo = 'bar' -%}
                {% include 'x.html' -%}
            """,
                "b.html": """
                {%- set foo = 'bar' -%}
                {% block test %}{% include 'x.html' %}{% endblock -%}
                """,
                "c.html": """
                {%- set foo = 'bar' -%}
                {% block test %}{% set foo = foo
                    %}{% include 'x.html' %}{% endblock -%}
            """,
                "x.html": """{{ foo }}|{{ test }}""",
            }))

        a = env.get_template("a.html")
        b = env.get_template("b.html")
        c = env.get_template("c.html")

        assert a.render(test="x").strip() == "bar|x"
        assert b.render(test="x").strip() == "bar|x"
        assert c.render(test="x").strip() == "bar|x"
Beispiel #4
0
 def test_choice_loader(self, choice_loader):
     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"
     pytest.raises(TemplateNotFound, env.get_template, "missing.html")
Beispiel #5
0
 def test_filesystem_loader_overlapping_names(self, filesystem_loader):
     res = os.path.dirname(filesystem_loader.searchpath[0])
     t2_dir = os.path.join(res, "templates2")
     # Make "foo" show up before "foo/test.html".
     filesystem_loader.searchpath.insert(0, t2_dir)
     e = Environment(loader=filesystem_loader)
     e.get_template("foo")
     # This would raise NotADirectoryError if "t2/foo" wasn't skipped.
     e.get_template("foo/test.html")
def test_dict_loader():
    env = Environment(loader=dict_loader)
    tmpl = env.get_template('justdict.html')
    assert tmpl.render().strip() == 'FOO'
    try:
        env.get_template('missing.html')
    except TemplateNotFound:
        pass
    else:
        raise AssertionError('expected template exception')
Beispiel #7
0
    def test_caches_template_based_on_mtime(self):
        filesystem_loader = loaders.FileSystemLoader(self.searchpath)

        env = Environment(loader=filesystem_loader)
        tmpl1 = env.get_template("test.html")
        tmpl2 = env.get_template("test.html")
        assert tmpl1 is tmpl2

        os.utime(os.path.join(self.searchpath, "test.html"), (time.time(), time.time()))
        tmpl3 = env.get_template("test.html")
        assert tmpl1 is not tmpl3
def test_memcached_loader():
    env = Environment(loader=memcached_loader)
    tmpl = env.get_template('test.html')
    assert tmpl.render().strip() == 'BAR'
    tmpl = env.get_template('foo/test.html')
    assert tmpl.render().strip() == 'FOO'
    try:
        env.get_template('missing.html')
    except TemplateNotFound:
        pass
    else:
        raise AssertionError('expected template exception')
Beispiel #9
0
 def test_limited_size_cache(self):
     mapping = {"one": "foo", "two": "bar", "three": "baz"}
     loader = loaders.DictLoader(mapping)
     env = Environment(loader=loader, cache_size=2)
     t1 = env.get_template("one")
     t2 = env.get_template("two")
     assert t2 is env.get_template("two")
     assert t1 is env.get_template("one")
     env.get_template("three")
     loader_ref = weakref.ref(loader)
     assert (loader_ref, "one") in env.cache
     assert (loader_ref, "two") not in env.cache
     assert (loader_ref, "three") in env.cache
Beispiel #10
0
    def test_caching(self):
        changed = False

        class TestLoader(loaders.BaseLoader):
            def get_source(self, environment, template):
                return u"foo", None, lambda: not changed

        env = Environment(loader=TestLoader(), cache_size=-1)
        tmpl = env.get_template("template")
        assert tmpl is env.get_template("template")
        changed = True
        assert tmpl is not env.get_template("template")
        changed = False
def test_package_loader():
    env = Environment(loader=package_loader)
    for x in xrange(2):
        tmpl = env.get_template('test.html')
        assert tmpl.render().strip() == 'BAR'
        try:
            env.get_template('missing.html')
        except TemplateNotFound:
            pass
        else:
            raise AssertionError('expected template exception')

        # second run in native mode (no pkg_resources)
        package_loader.force_native = True
        del package_loader._load_func
Beispiel #12
0
 def model_run(self, model_context):
     context = self._build_context(model_context)
     # mostrar el reporte
     fileloader = PackageLoader("canasta", "templates")
     env = Environment(loader=fileloader)
     t = env.get_template("precios.html")
     yield PrintHtml(t.render(context))
Beispiel #13
0
class BuiltinTemplates(TemplateBridge):
    def init(self, builder):
        self.templates = {}
        base_templates_path = path.join(path.dirname(__file__), 'templates')
        ext_templates_path = [path.join(builder.confdir, dir)
                              for dir in builder.config.templates_path]
        self.templates_path = [base_templates_path] + ext_templates_path
        loader = SphinxFileSystemLoader(base_templates_path, ext_templates_path)
        if builder.translator is not None:
            self.jinja_env = TranslatorEnvironment(loader=loader,
                    friendly_traceback=False, translator=builder.translator)
        else:
            self.jinja_env = Environment(loader=loader,
                    # disable traceback, more likely that something
                    # in the application is broken than in the templates
                    friendly_traceback=False)

    def newest_template_mtime(self):
        return max(mtimes_of_files(self.templates_path, '.html'))

    def render(self, template, context):
        if template in self.templates:
            return self.templates[template].render(context)
        templateobj = self.templates[template] = \
                      self.jinja_env.get_template(template)
        return templateobj.render(context)
Beispiel #14
0
 def test_set_and_include(self):
     env = Environment(loader=DictLoader(
         {
             "inc": "bar",
             "main": '{% set foo = "foo" %}{{ foo }}{% include "inc" %}',
         }))
     assert env.get_template("main").render() == "foobar"
Beispiel #15
0
 def model_run(self, model_context):
     context = self._build_context(model_context)
     # mostrar el reporte
     fileloader = PackageLoader('m2000', 'templates')
     env = Environment(loader=fileloader)
     t = env.get_template('cartera_perdida_x_incobrable.html')
     yield PrintHtml(t.render(context))
Beispiel #16
0
 def model_run(self, model_context):
     context = self._build_context(model_context)
     # mostrar el reporte
     fileloader = PackageLoader('m2000', 'templates')
     env = Environment(loader=fileloader)
     t = env.get_template('cartera_finalizados_sin_saldar.html')
     yield PrintHtml(t.render(context))
Beispiel #17
0
class BuiltinTemplates(TemplateBridge):
    def init(self, builder):
        self.templates = {}
        base_templates_path = path.join(path.dirname(__file__), 'templates')
        ext_templates_path = [
            path.join(builder.confdir, dir)
            for dir in builder.config.templates_path
        ]
        self.templates_path = [base_templates_path] + ext_templates_path
        loader = SphinxFileSystemLoader(base_templates_path,
                                        ext_templates_path)
        if builder.translator is not None:
            self.jinja_env = TranslatorEnvironment(
                loader=loader,
                friendly_traceback=False,
                translator=builder.translator)
        else:
            self.jinja_env = Environment(
                loader=loader,
                # disable traceback, more likely that something
                # in the application is broken than in the templates
                friendly_traceback=False)

    def newest_template_mtime(self):
        return max(mtimes_of_files(self.templates_path, '.html'))

    def render(self, template, context):
        if template in self.templates:
            return self.templates[template].render(context)
        templateobj = self.templates[template] = \
                      self.jinja_env.get_template(template)
        return templateobj.render(context)
Beispiel #18
0
 def model_run(self, model_context):
     context = self._build_context(model_context)
     # mostrar el reporte
     fileloader = PackageLoader('m2000', 'templates')
     env = Environment(loader=fileloader)
     t = env.get_template('recaudacion_potencial_total_x_barrio.html')
     yield PrintHtml(t.render(context))
Beispiel #19
0
        def render(printer):
            client_address = "<br/>".join(["2 Azalea St.", "Fredericksburg", "22406 VA"])

            import datetime

            ts = datetime.datetime.today()
            datestring = "Date: %s/%s/%s" % (ts.month, ts.day, ts.year)

            view_content = view.toHtml()
            context = {
                "logo": icon,
                "company_name": "Conceptive Engineering",
                "company_address_1": "L. Van Bauwelstraat 16",
                "company_address_2": "2220 Heist-op-den-Berg",
                "city": "Belgium",
                "date": datestring,
                "client_address": client_address,
                "client_name": "Client",
                "content": view_content,
                "signature": "M. Anager",
            }

            from jinja import Environment, FileSystemLoader

            fileloader = FileSystemLoader(settings.CAMELOT_TEMPLATES_DIRECTORY)
            e = Environment(loader=fileloader)
            t = e.get_template("base.html")
            html = t.render(context)

            doc = QtGui.QTextDocument()
            doc.setHtml(html)
            doc.print_(self.printer)
Beispiel #20
0
 def test_scoped_block_after_inheritance(self, env):
     env = Environment(loader=DictLoader({
         "layout.html":
         """
         {% block useless %}{% endblock %}
         """,
         "index.html":
         """
         {%- extends 'layout.html' %}
         {% from 'helpers.html' import foo with context %}
         {% block useless %}
             {% for x in [1, 2, 3] %}
                 {% block testing scoped %}
                     {{ foo(x) }}
                 {% endblock %}
             {% endfor %}
         {% endblock %}
         """,
         "helpers.html":
         """
         {% macro foo(x) %}{{ the_foo + x }}{% endmacro %}
         """,
     }))
     rv = env.get_template("index.html").render(the_foo=42).split()
     assert rv == ["43", "44", "45"]
Beispiel #21
0
 def model_run(self, model_context):
     context = self._build_context(model_context)
     # mostrar el reporte
     fileloader = PackageLoader('m2000', 'templates')
     env = Environment(loader=fileloader)
     t = env.get_template('indicadores.html')
     yield PrintHtmlLandscape(t.render(context))
Beispiel #22
0
def load_template(config, templateName):
    """"Charge un template"""
    if config.template_dir == "":
        environment = Environment(loader=PackageLoader('tracforge', 'templates'))
    else:
        environment = Environment(loader=FileSystemLoader(config.template_dir))
    return environment.get_template(templateName)
Beispiel #23
0
 def test_context_include_with_overrides(self, test_env):
     env = Environment(loader=DictLoader(
         dict(
             main=
             "{% for item in [1, 2, 3] %}{% include 'item' %}{% endfor %}",
             item="{{ item }}",
         )))
     assert env.get_template("main").render() == "123"
Beispiel #24
0
 def test_loop_include(self):
     env = Environment(loader=DictLoader({
         "inc":
         "{{ i }}",
         "main":
         '{% for i in [1, 2, 3] %}{% include "inc" %}{% endfor %}',
     }))
     assert env.get_template("main").render() == "123"
Beispiel #25
0
 def test_scopes_and_include(self):
     env = Environment(loader=DictLoader(
         {
             "include.html": "{{ var }}",
             "base.html": '{% include "include.html" %}',
             "child.html": '{% extends "base.html" %}{% set var = 42 %}',
         }))
     t = env.get_template("child.html")
     assert t.render() == "42"
Beispiel #26
0
 def test_preserve_blocks(self, env):
     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"
Beispiel #27
0
 def test_dynamic_inheritance(self, env):
     env = Environment(loader=DictLoader(
         {
             "master1": "MASTER1{% block x %}{% endblock %}",
             "master2": "MASTER2{% block x %}{% endblock %}",
             "child":
             "{% extends master %}{% block x %}CHILD{% endblock %}",
         }))
     tmpl = env.get_template("child")
     for m in range(1, 3):
         assert tmpl.render(master="master%d" % m) == "MASTER%dCHILD" % m
Beispiel #28
0
    def model_run(self, model_context):
        obj = model_context.get_object()

        deuda_final = obj.prestamo * (1 + obj.tasa_interes)
        redondeo = 0.5
        cuota_sin_redondeo = round(deuda_final / obj.cuotas)
        if deuda_final - (obj.cuotas - 1) * cuota_sin_redondeo > cuota_sin_redondeo:
            cuota_calculada = cuota_sin_redondeo + redondeo
        else:
            cuota_calculada = cuota_sin_redondeo
        # debido al redondeo, puede ocurrir que la deuda se cancela antes.
        # obtener el monto de la ultima cuota
        for i in range(1, obj.cuotas):
            monto_ultima_cuota = deuda_final - cuota_calculada * (obj.cuotas - i)
            if monto_ultima_cuota >= 0:
                break

        # generar la planilla
        detalle = []
        if obj.para_construccion:
            detalle = [] #self._detalle_planilla_aleman(obj)
            template = 'planilla_pagos_aleman.html'
        else:
            detalle = self._detalle_planilla(obj, cuota_calculada, deuda_final)
            template = 'planilla_pagos.html'

        context = {
            'anio': datetime.date.today().year,
            'comentarios': obj.beneficiaria.comentarios,
            'saldo_anterior': money_fmt(obj.saldo_anterior),
            'monto_cheque': money_fmt(obj.monto_cheque),
            'fecha_entrega': obj.fecha_entrega,
            'deuda_inicial': money_fmt(obj.prestamo),
            'deuda_final': money_fmt(deuda_final),
            'nro_credito': obj.nro_credito,
            'cuotas': obj.cuotas,
            'cuota_calculada': money_fmt(cuota_calculada),
            'monto_ultima_cuota': money_fmt(monto_ultima_cuota),
            'fecha': datetime.date.today(),
            'pagado_a_fecha': money_fmt(obj.total_pagos),
            'beneficiaria': '%s %s' % (obj.beneficiaria.nombre, obj.beneficiaria.apellido),
            'dni': obj.beneficiaria.dni,
            'telefono': obj.beneficiaria.telefono,
            'domicilio': obj.beneficiaria.domicilio,
            'grupo': obj.beneficiaria.grupo,
            'detalle': detalle,

        }
        # mostrar el reporte
        fileloader = PackageLoader('m2000', 'templates')
        env = Environment(loader=fileloader)
        t = env.get_template(template)
        yield PrintHtml(t.render(context))
def test_super():
    env = Environment(loader=DictLoader({
        'a': '{% block intro %}INTRO{% endblock %}|'
             'BEFORE|{% block data %}INNER{% endblock %}|AFTER',
        'b': '{% extends "a" %}{% block data %}({{ '
             'super() }}){% endblock %}',
        'c': '{% extends "b" %}{% block intro %}--{{ '
             'super() }}--{% endblock %}\n{% block data '
             '%}[{{ super() }}]{% endblock %}'
    }))
    tmpl = env.get_template('c')
    assert tmpl.render() == '--INTRO--|BEFORE|[(INNER)]|AFTER'
Beispiel #30
0
 def test_multi_inheritance(self, env):
     env = Environment(loader=DictLoader({
         "master1":
         "MASTER1{% block x %}{% endblock %}",
         "master2":
         "MASTER2{% block x %}{% endblock %}",
         "child":
         """{% if master %}{% extends master %}{% else %}{% extends
             'master1' %}{% endif %}{% block x %}CHILD{% endblock %}""",
     }))
     tmpl = env.get_template("child")
     assert tmpl.render(master="master2") == "MASTER2CHILD"
     assert tmpl.render(master="master1") == "MASTER1CHILD"
     assert tmpl.render() == "MASTER1CHILD"
Beispiel #31
0
def render(filename, data={}):
    import cherrypy
    from jinja import Environment, FileSystemLoader

    environment = Environment(loader=FileSystemLoader("views"))

    data["VERSION"] = encode_unicode(file("VERSION").read()).strip()
    try:
        data["flash"] = get_flash()
        data["flash_class"] = cherrypy.session["flash_class"]
    except KeyError:
        pass
    data.update(helpers)
    data["User"] = cherrypy.session.get("User")
    return environment.get_template(filename + ".jinja").render(data)
Beispiel #32
0
def app(environ, start_response):
    response_code = '200 OK'
    response_type = ('Content-Type', 'text/HTML')
    start_response(response_code, [response_type])

    for item in assets:
        separator = item.split('.')
        if separator[1] == 'js':
            js.append(item)
        elif separator[1] == 'css':
            css.append(item)

    env = Environment(loader=FileSystemLoader('.'))
    template = env.get_template('index.html')
    print(template.render(css0=css, js0=js))
Beispiel #33
0
 def test_super(self, env):
     env = Environment(loader=DictLoader({
         "a":
         "{% block intro %}INTRO{% endblock %}|"
         "BEFORE|{% block data %}INNER{% endblock %}|AFTER",
         "b":
         '{% extends "a" %}{% block data %}({{ '
         "super() }}){% endblock %}",
         "c":
         '{% extends "b" %}{% block intro %}--{{ '
         "super() }}--{% endblock %}\n{% block data "
         "%}[{{ super() }}]{% endblock %}",
     }))
     tmpl = env.get_template("c")
     assert tmpl.render() == "--INTRO--|BEFORE|[(INNER)]|AFTER"
Beispiel #34
0
    def model_run(self, model_context):
        from camelot.view.action_steps import PrintHtml
        import datetime
        import os
        from jinja import Environment, FileSystemLoader
        from pkg_resources import resource_filename

        fileloader = FileSystemLoader(resource_filename(rms.__name__, 'templates'))
        e = Environment(loader=fileloader)
        resursa = model_context.get_object()
        context = {
            'header': resursa.nume,
            'title': 'Raport resurse umane',
            'style': '.label { font-weight:bold; }',
            'persoana': resursa,
            'footer': str(datetime.datetime.now().year)
        }
        t = e.get_template('resurse_umane.html')
        yield PrintHtml(t.render(context))
Beispiel #35
0
    def get(self):

        providers = [{'title': p.title, 'url': p.url, \
                      'example_url': p.example_url, \
                      'description': p.__doc__} \
                     for p in self.providers]
        providers.sort(lambda x, y: cmp(x['title'].lower(), y['title'].lower()))

        if 'Development' in os.environ['SERVER_SOFTWARE']:
            production = False
        else:
            production = True

        env = Environment(loader=FileSystemLoader(os.path.dirname(__file__)))
        tmpl = env.get_template('index.jinja')

        hostname = os.environ['HTTP_HOST'].lower()
        self.response.out.write(tmpl.render(providers=providers,
                                            production=production, hostname=hostname))
Beispiel #36
0
    def model_run(self, model_context):
        from camelot.view.action_steps import PrintHtml
        import datetime
        import os
        from jinja import Environment, FileSystemLoader
        from pkg_resources import resource_filename

        fileloader = FileSystemLoader(
            resource_filename(rms.__name__, 'templates'))
        e = Environment(loader=fileloader)
        resursa = model_context.get_object()
        context = {
            'header': resursa.nume,
            'title': 'Raport resurse',
            'style': '.label { font-weight:bold; }',
            'activitati': resursa.activitati,
            'footer': str(datetime.datetime.now().year)
        }
        t = e.get_template('resurse_logistice.html')
        yield PrintHtml(t.render(context))
Beispiel #37
0
    def get(self):

        providers = [{'title': p.title, 'url': p.url, \
                    'example_url': p.example_url, \
                    'description': p.__doc__} \
                        for p in self.providers]
        providers.sort(
            lambda x, y: cmp(x['title'].lower(), y['title'].lower()))

        if 'Development' in os.environ['SERVER_SOFTWARE']:
            production = False
        else:
            production = True

        env = Environment(loader=FileSystemLoader(os.path.dirname(__file__)))
        tmpl = env.get_template('index.jinja')

        hostname = os.environ['HTTP_HOST'].lower()
        self.response.out.write(
            tmpl.render(providers=providers,
                        production=production,
                        hostname=hostname))
Beispiel #38
0
    def model_run(self, model_context):
        obj = model_context.get_object()

        monto_cuota = obj.monto_cheque * (1 + obj.tasa_interes) / obj.cuotas
        # la 1era semana no paga cuota. Recien a los 14 dias de recibido el cheque tiene que pagar la primer cuota.
        fecha_1ra_cuota = obj.fecha_entrega + datetime.timedelta(weeks=2)
        fecha_ultima_cuota = obj.fecha_entrega + datetime.timedelta(weeks=obj.cuotas + 1)

        context = {
            'header_image_filename': header_image_filename(),
            'firma_presidente_filename': firma_presidente_filename(),
            'firma_tesorero_filename': firma_tesorero_filename(),
            'beneficiaria': '%s %s' % (obj.beneficiaria.nombre, obj.beneficiaria.apellido),
            'dni': spacer(obj.beneficiaria.dni),
            'fecha_nac': spacer(obj.beneficiaria.fecha_nac),
            'estado_civil': spacer(obj.beneficiaria.estado_civil),
            'domicilio': spacer(obj.beneficiaria.domicilio),
            'ciudad': obj.beneficiaria.barrio.domicilio_pago.ciudad.nombre,
            'provincia': obj.beneficiaria.barrio.domicilio_pago.ciudad.provincia.nombre,
            'emprendimiento': obj.rubro.actividad,
            'tasa_interes_mensual': float_fmt(obj.tasa_interes * 100 * 4 / obj.cuotas),  # 4 -> semanas en un mes
            'cuotas': obj.cuotas,
            'cuotas_letras': nro_en_letras(obj.cuotas),
            'monto_prestamo': money_fmt(obj.prestamo, 2),
            'monto_prestamo_letras': nro_en_letras(obj.prestamo),
            'monto_cuota_letras': nro_en_letras(monto_cuota),
            'monto_cuota': money_fmt(monto_cuota, 2),
            'dia_1ra_cuota': fecha_1ra_cuota.day,
            'mes_1ra_cuota_letras': mes_en_letras(fecha_1ra_cuota.month),
            'anio_1ra_cuota': fecha_1ra_cuota.year,
            'dia_ultima_cuota': fecha_ultima_cuota.day,
            'mes_ultima_cuota_letras': mes_en_letras(fecha_ultima_cuota.month),
            'anio_ultima_cuota': fecha_ultima_cuota.year,
            'domicilio_pago': obj.beneficiaria.barrio.domicilio_pago.nombre,
        }
        fileloader = PackageLoader('m2000', 'templates')
        env = Environment(loader=fileloader)
        t = env.get_template('contrato_mutuo.html')
        yield PrintHtml(t.render(context))
Beispiel #39
0
    def model_run(self, model_context):
        from camelot.view.action_steps import PrintHtml
        import datetime
        import os
        from jinja import Environment, FileSystemLoader
        from pkg_resources import resource_filename

        fileloader = FileSystemLoader(resource_filename(rms.__name__, 'templates'))
        e = Environment(loader=fileloader)
        activitate = model_context.get_object()
        context = {
            'header': activitate.nume,
            'title': 'Raport activitate',
            'style': '.label { font-weight:bold; }',
            'coordonator': activitate.coordonator,
            'aprobata': activitate.aprobata,
            'membrii': activitate.membrii,
            'res_fin': activitate.res_fin,
            'res_log': activitate.res_logistice,
            'footer': str(datetime.datetime.now().year)
        }
        t = e.get_template('activitate.html')
        yield PrintHtml(t.render(context))
    def model_run(self, model_context):
        from camelot.view.action_steps import PrintHtml
        import datetime
        import os
        from jinja import Environment, FileSystemLoader
        from pkg_resources import resource_filename

        fileloader = FileSystemLoader(
            resource_filename(rms.__name__, 'templates'))
        e = Environment(loader=fileloader)
        activitate = model_context.get_object()
        context = {
            'header': activitate.nume,
            'title': 'Raport activitate',
            'style': '.label { font-weight:bold; }',
            'coordonator': activitate.coordonator,
            'aprobata': activitate.aprobata,
            'membrii': activitate.membrii,
            'res_fin': activitate.res_fin,
            'res_log': activitate.res_logistice,
            'footer': str(datetime.datetime.now().year)
        }
        t = e.get_template('activitate.html')
        yield PrintHtml(t.render(context))
def test_choice_loader():
    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'
    try:
        env.get_template('missing.html')
    except TemplateNotFound:
        pass
    else:
        raise AssertionError('expected template exception')

    # this should raise an TemplateNotFound error with the
    # correct name
    try:
        env.get_template('brokenimport.html')
    except TemplateNotFound, e:
        assert e.name == 'missing.html'
Beispiel #42
0
from __future__ import print_function

from jinja import Environment
from jinja.loaders import DictLoader

env = Environment(loader=DictLoader(
    {
        "a": "[A[{% block body %}{% endblock %}]]",
        "b": "{% extends 'a' %}{% block body %}[B]{% endblock %}",
        "c":
        "{% extends 'b' %}{% block body %}###{{ super() }}###{% endblock %}",
    }))
print(env.get_template("c").render())
Beispiel #43
0
def build_examples():
    funcs = [f for f in listfunc() if f.__name__.startswith('test_')]
    examples = []
    categories = []
    for f in funcs:
        fdoc = f.__doc__.split('\n')
        cat, title = fdoc[1].strip().split('/')
        doc = markdown2.markdown('\n'.join([l.strip() for l in fdoc[2:]]))
        name = f.__name__.split('test_')[1]
        json = ''
        if f():
            json = f().render()
        code = inspect.getsource(f) 
        cstart = code.find("'''")
        cend = code.find("'''", cstart+3)+3
        code = code[:cstart]+ code[cend:]
        
        try:
            from pygments import highlight
            from pygments.lexers import get_lexer_by_name
            from pygments.formatters import HtmlFormatter

            lexer = get_lexer_by_name("python", stripall=True)
            formatter = HtmlFormatter(linenos=False, cssclass="syntax")
            code = highlight(code, lexer, formatter)
        except:
            pass 
        if cat not in categories:
            categories.append(cat)
            
        example = {
            'name': name,
            'title': title,
            'cat':cat,
            'doc': doc,
            'code': code,
            'datafile': 'data/%s.json' % (name, ),
            'json': json
            } 
        examples.append(example)
        
    #generate data files & sidebar links
    for e in examples:
        outf = open(e['datafile'], 'w')
        outf.write(e['json'])
        outf.close()     

    sidebar = '<dl>%s</dl>'
    links = []
    for cat in categories:
        links.append('<dt class="el2">%s</dt><dd>' % cat)
        for e in examples: #inefficient.. much
            if cat == e['cat']:
                links.append('<li><a href="%s">%s</a></li>' %(e['name']+'.html', e['title']))      
        links.append('</dd>')
    sidebar = sidebar % '\n'.join(links)
        
    #generate demo-html files
    env = Environment(loader=FileSystemLoader('templates'))
    tmpl = env.get_template('code.html')
    
    
    for e in examples:
        fname = e['name']+'.html'
        outf = open(fname, 'w')
        e.update({'sidebar':sidebar})
        output = tmpl.render(**e) 
        outf.write(output)
        outf.close()

    #generate doc-html files
    env = Environment(loader=FileSystemLoader('templates'))
    tmpl = env.get_template('doc.html')


    for e in docs:
        fname = e['name']+'.html'
        outf = open(fname, 'w')
        e.update({'sidebar':sidebar})
        output = tmpl.render(**e) 
        outf.write(output)
        outf.close()        
        
    print 'Build complete.'
    print 'Run ./start.sh and visit http://localhost:8000/'
Beispiel #44
0
    def _init_(self, app):
        self.app = app
    
     def __call__(self, environ, start_response):
        response = self.app(environ, start_response).decode() 
        if response.find('<body>') > -1:
            head1, head = response.split('<head>')
            datahead, endhead = head.split('</head>')
            head2, body = endhead.split('<body>')
            databody, endbody = body.split('</body>')

            yield (head1 + data + endbody).encode()  
        else:
            yield (response).encode()  
        def app(environ, start_response):
    
    response_code = '200 OK'
    response_type = ('Content-Type', 'text/HTML')
    start_response(response_code, [response_type])
    return ''''''

app = WsgiTopBottomMiddleware(app)

request = Request.blank('/index.html')

env = Environment(loader=FileSystemLoader('.'))
template = env.get_template('index.html')
print(template.render(js=scripts, css=styles))

print(request.get_response(app))
Beispiel #45
0
# test file for block super support
import jdebug
from jinja import Environment, DictLoader

env = Environment(loader=DictLoader({
    'a': '{% block intro %}INTRO{% endblock %}|BEFORE|{% block data %}INNER{% endblock %}|AFTER',
    'b': '{% extends "a" %}{% block data %}({{ super() }}){% endblock %}',
    'c': '{% extends "b" %}{% block intro %}--{{ super() }}--{% endblock %}\n{% block data %}[{{ super() }}]{% endblock %}'
}))

tmpl = env.get_template('c')
print tmpl.render()
    'syntax_broken': '''\
This is an included template
{% raw %}just some foo''',
    'multiple_broken': '''\
Just some context:
{% include 'macro_broken' %}
{{ broken() }}
''',
    'macro_broken': '''\
{% macro broken %}
    {{ 1 / 0 }}
{% endmacro %}
'''
}))
e.globals['fire_multiple_broken'] = lambda: \
    e.get_template('multiple_broken').render()

FAILING_STRING_TEMPLATE = '{{ 1 / 0 }}'
BROKEN_STRING_TEMPLATE = '{% if foo %}...{% endfor %}'


def broken():
    raise RuntimeError("I'm broken")


def test(environ, start_response):
    path = environ.get('PATH_INFO' or '/')
    try:
        tmpl = e.get_template(path)
    except TemplateNotFound:
        if path == '/syntax_from_string':