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"
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))
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")
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")
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"
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"
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"]
def babel_extract(fileobj, keywords, comment_tags, options): """ Simple extractor to get some basic Babel support. """ env = Environment() for lineno, sg, pl in env.get_translations_for_string(fileobj.read()): yield lineno, None, (sg, pl), ''
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)
def test_raw4(self, env): # The trailing dash of the {% raw -%} cleans both the spaces and # newlines up to the first character of data. env = Environment(lstrip_blocks=True, trim_blocks=False) tmpl = env.from_string( "bar\n{%- raw -%}\n\n \n 2 spaces\n space{%- endraw -%}\nfoo") assert tmpl.render() == "bar2 spaces\n spacefoo"
def test_overlay_scopes(self): class MagicScopeExtension(Extension): tags = set(["overlay"]) def parse(self, parser): node = nodes.OverlayScope(lineno=next(parser.stream).lineno) node.body = list( parser.parse_statements(("name:endoverlay", ), drop_needle=True)) node.context = self.call_method("get_scope") return node def get_scope(self): return {"x": [1, 2, 3]} env = Environment(extensions=[MagicScopeExtension]) tmpl = env.from_string(""" {{- x }}|{% set z = 99 %} {%- overlay %} {{- y }}|{{ z }}|{% for item in x %}[{{ item }}]{% endfor %} {%- endoverlay %}| {{- x -}} """) assert tmpl.render(x=42, y=23) == "42|23|99|[1][2][3]|42"
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))
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)
def test_raw3(self, env): # The second newline after baz exists because it is AFTER the # {% raw %} and is ignored. env = Environment(lstrip_blocks=True, trim_blocks=True) tmpl = env.from_string( "bar\n{% raw %}\n {{baz}}2 spaces\n{% endraw %}\nfoo") assert tmpl.render(baz="test") == "bar\n\n {{baz}}2 spaces\nfoo"
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))
def test_lstrip_blocks_false_with_no_lstrip(self, env): # Test that + is a NOP (but does not cause an error) if lstrip_blocks=False env = Environment(lstrip_blocks=False, trim_blocks=False) tmpl = env.from_string(""" {% if True %}\n {% endif %}""") assert tmpl.render() == " \n " tmpl = env.from_string(""" {%+ if True %}\n {%+ endif %}""") assert tmpl.render() == " \n "
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))
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))
def test_import_from_with_context(self): env = Environment(loader=DictLoader( {"a": "{% macro x() %}{{ foobar }}{% endmacro %}"})) t = env.from_string( "{% set foobar = 42 %}{% from 'a' import x with context %}{{ x() }}" ) assert t.render() == "42"
def test_basic_scope_behavior(self): # This is what the old with statement compiled down to class ScopeExt(Extension): tags = set(["scope"]) def parse(self, parser): node = nodes.Scope(lineno=next(parser.stream).lineno) assignments = [] while parser.stream.current.type != "block_end": lineno = parser.stream.current.lineno if assignments: parser.stream.expect("comma") target = parser.parse_assign_target() parser.stream.expect("assign") expr = parser.parse_expression() assignments.append( nodes.Assign(target, expr, lineno=lineno)) node.body = assignments + list( parser.parse_statements( ("name:endscope", ), drop_needle=True)) return node env = Environment(extensions=[ScopeExt]) tmpl = env.from_string("""\ {%- scope a=1, b=2, c=b, d=e, e=5 -%} {{ a }}|{{ b }}|{{ c }}|{{ d }}|{{ e }} {%- endscope -%} """) assert tmpl.render(b=3, e=4) == "1|2|2|4|5"
def configure(convert_filters=DEFAULT_FILTERS, loader=None, **options): """ Initialize the system. """ global env if env: warnings.warn("Jinja already initialized.") return # setup environment if loader is None: loaders = tuple(FileSystemLoader(l) for l in settings.TEMPLATE_DIRS) if not loaders: loader = None elif len(loaders) == 1: loader = loaders[0] else: loader = ChoiceLoader(loaders) env = Environment(loader=loader, **options) # convert requested filters for name in convert_filters: env.filters[name] = convert_django_filter(name) # Register URL template tag env.globals[url] = url # import templatetags of installed apps for app in settings.INSTALLED_APPS: try: __import__(app + '.templatetags') except ImportError: pass
def test_nonvolatile(self): env = Environment(extensions=["jinja.ext.autoescape"], autoescape=True) tmpl = env.from_string('{{ {"foo": "<test>"}|xmlattr|escape }}') assert tmpl.render() == ' foo="<test>"' tmpl = env.from_string('{% autoescape false %}{{ {"foo": "<test>"}' "|xmlattr|escape }}{% endautoescape %}") assert tmpl.render() == " foo="&lt;test&gt;""
def test_debug(self): env = Environment(extensions=["jinja.ext.debug"]) t = env.from_string("Hello\n{% debug %}\nGoodbye") out = t.render() for value in ("context", "cycler", "filters", "abs", "tests", "!="): assert "'{}'".format(value) in out
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"
def test_comment_syntax(self, env): env = Environment("<!--", "-->", "${", "}", "<!--#", "-->") tmpl = env.from_string("""\ <!--# I'm a comment, I'm not interesting -->\ <!-- for item in seq ---> ${item} <!--- endfor -->""") assert tmpl.render(seq=list(range(5))) == "01234"
def test_php_syntax(self, env): env = Environment("<?", "?>", "<?=", "?>", "<!--", "-->") tmpl = env.from_string("""\ <!-- I'm a comment, I'm not interesting -->\ <? for item in seq -?> <?= item ?> <?- endfor ?>""") assert tmpl.render(seq=list(range(5))) == "01234"
def test_urlize_rel_policy(self): env = Environment() env.policies["urlize.rel"] = None tmpl = env.from_string( '{{ "foo http://www.example.com/ bar"|urlize }}') assert tmpl.render() == ( 'foo <a href="http://www.example.com/">http://www.example.com/</a> bar' )
def test_include(self, env_trim): env_trim = Environment( loader=DictLoader( {"include": "{% macro test(foo) %}[{{ foo }}]{% endmacro %}"} ) ) tmpl = env_trim.from_string('{% from "include" import test %}{{ test("foo") }}') assert tmpl.render() == "[foo]"
def test_do(self): env = Environment(extensions=["jinja.ext.do"]) tmpl = env.from_string(""" {%- set items = [] %} {%- for char in "foo" %} {%- do items.append(loop.index0 ~ char) %} {%- endfor %}{{ items|join(', ') }}""") assert tmpl.render() == "0f, 1o, 2o"
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"
def test_erb_syntax(self, env): env = Environment("<%", "%>", "<%=", "%>", "<%#", "%>") tmpl = env.from_string("""\ <%# I'm a comment, I'm not interesting %>\ <% for item in seq -%> <%= item %> <%- endfor %>""") assert tmpl.render(seq=list(range(5))) == "01234"
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"
def test_super_in_scoped_block(self, env): env = Environment(loader=DictLoader({ "master.html": "{% for item in seq %}[{% block item scoped %}" "{{ item }}{% endblock %}]{% endfor %}" })) t = env.from_string('{% extends "master.html" %}{% block item %}' "{{ super() }}|{{ item * 2 }}{% endblock %}") assert t.render(seq=list(range(5))) == "[0|0][1|2][2|4][3|6][4|8]"
def test_no_variable_block(): env = Environment('{%', '%}', None, None) tmpl = env.from_string(NO_VARIABLE_BLOCK) assert tmpl.render(foo=42, seq=range(2)).splitlines() == [ '42', '01', 'foo is 42', '42 foos' ]
def test_join(self, env): tmpl = env.from_string('{{ [1, 2, 3]|join("|") }}') out = tmpl.render() assert out == "1|2|3" env2 = Environment(autoescape=True) tmpl = env2.from_string( '{{ ["<foo>", "<span>foo</span>"|safe]|join }}') assert tmpl.render() == "<foo><span>foo</span>"
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')
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')
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'
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 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
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)
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)
def test_extends_position(): env = Environment(loader=DictLoader({ 'empty': '[{% block empty %}{% endblock %}]' })) tests = [ ('{% extends "empty" %}', '[!]'), (' {% extends "empty" %}', '[!]'), (' !\n', ' !\n!'), ('{# foo #} {% extends "empty" %}', '[!]'), ('{% set foo = "blub" %}{% extends "empty" %}', None) ] for tmpl, expected_output in tests: try: tmpl = env.from_string(tmpl + '{% block empty %}!{% endblock %}') except TemplateSyntaxError: assert expected_output is None, 'got syntax error' else: assert expected_output == tmpl.render()
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))
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))
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))
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'
def test_smarty_syntax(): env = Environment('{', '}', '{', '}', '{*', '*}') tmpl = env.from_string(SMARTY_SYNTAX) assert tmpl.render(seq=range(5)) == '01234'
def test_comment_syntax(): env = Environment('<!--', '-->', '${', '}', '<!--#', '-->') tmpl = env.from_string(COMMENT_SYNTAX) assert tmpl.render(seq=range(5)) == '01234'
def test_erb_syntax(): env = Environment('<%', '%>', '<%=', '%>', '<%#', '%>') tmpl = env.from_string(ERB_SYNTAX) assert tmpl.render(seq=range(5)) == '01234'
def test_php_syntax(): env = Environment('<?', '?>', '<?=', '?>', '<!--', '-->') tmpl = env.from_string(PHP_SYNTAX) assert tmpl.render(seq=range(5)) == '01234'
def test_nonlocal_set(): env = Environment() env.globals['outer'] = 42 tmpl = env.from_string(NONLOCALSET) assert tmpl.render() == '9' assert env.globals['outer'] == 42
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/'