def test_overlay(self): td = Domain(DEFAULT_DIR) t = td.get_template('overlay.html') self.assertEqual( eval("dict(%s)"%(t.eval_overlay)), dict(name="base.html")) space, overlay = t.get_space_overlay() self.failUnless(space is True) self.failUnless(t.labels == ["content"]) # t.evoque(title="positive overlay test", parametrized="and happy") chain_pos = td.get_template('overlay_chain_pos.html') self.assertEqual( eval("dict(%s)"%(chain_pos.eval_overlay)), dict(name="overlay_mid.html")) space, overlay = chain_pos.get_space_overlay() self.failUnless(space is True) self.failUnless(chain_pos.labels == ["content"]) # chain_pos.evoque(title="positive overlay test", parametrized="and happy") chain_neg = td.get_template('overlay_chain_neg.html') self.assertEqual(eval("dict(%s)"%(chain_neg.eval_overlay)), dict(name="overlay_mid.html", space="negative")) space, overlay = chain_neg.get_space_overlay() self.failUnless(space is False) self.failUnless(chain_neg.labels == ["content", "footer"]) # chain_neg.evoque(title="negative overlay test", parametrized="and happy") b = td.get_template('base.html') self.failUnless(b.labels == ["header", "content", "footer"]) self.failIf(b.eval_overlay is not None) self.assertRaises((TypeError,), b.get_space_overlay)
def load(self,template,vars): dp=os.path.dirname(template) if dp != '': self.domain=dp filename=os.path.basename(template) try: d=Domain(self.domain, quoting=None, errors=4) # fixme: what do we really want for quoting? t=Domain(self.domain, errors=4).get_template(filename, quoting="str") # fixme: why create two Domains? except Exception as e: print "(domain is %s)" % self.domain raise e evars=evoque_dict() # special dict that returns missing keys as "${key}" evars.update(vars) yaml_txt=t.evoque(evars) # fix eval errors: # fixed_yaml=re.sub('\[EvalError\(([a-z_]+)\)]', "${\g<1>}", yaml_txt) # ooh, magic! great. # fixed_yaml=re.sub('\[NameError: name ' ([a-z_]+)\)]', "${\g<1>}", yaml_txt) # ooh, magic! great. # fixed_yaml=re.sub('<built-in function ([a-z_]+)>', "${\g<1>}", fixed_yaml) # christ, more magic # warn("syml.load: fixed_yaml is %s" % fixed_yaml) d=yaml.load(yaml_txt) # "fix" config; ie, resolve referenced values d=self._fix_hash(d,d) return d
def load(self): # get globals if necessary if (self.globals == {}) and self.globals_file: f = open(self.globals_file, "r") self.globals = yaml.load(f) f.close # read config template (with globals) if not self.config_file: raise Exception("no config_file") if not self.domain: try: self.domain = self.globals["domain"] except: self.domain = os.getcwd() print "warning: looking for globals.yml in local directory!" try: t = Domain(self.domain).get_template(self.config_file) except Exception as e: print "(domain is %s)" % self.domain raise e conf_yaml = t.evoque(self.globals) conf = yaml.load(conf_yaml) # "fix" config; ie, resolve referenced values conf = self._fix_hash(conf, conf) conf.update({"globals": self.globals}) self.config = conf
def write_rnaseq_script(globals,pipeline,sample): domain=globals['domain'] d=Domain(domain) t=d.get_template(globals['rnaseq_template']) # build up list of rnaseq.steps to be included in the final script: # augment globals hash with rnaseq vars: vars={'globals_file':'globals.yml', 'rnaseq_steps':pipeline.as_python(), 'steps_syml':os.path.join(globals['python_lib'],'pipeline.steps.syml'), # hardcoded (for now?) 'sample_yml':sample.conf_file, 'timestamp':sample.timestamp(), } vars.update(globals) rnaseq_script=t.evoque(vars) # write script: os.mkdir(os.path.join(sample.working_dir(),'starflow','rnaseq')) fn=pipeline.script_filename('starflow/rnaseq','rnaseq','py') f=open(fn, 'w') f.write(rnaseq_script) f.close print "%s written" % fn return fn
def test_get_mixed_name_src(self): td = Domain(DEFAULT_DIR, restricted=RESTRICTED, errors=ERRORS) name = '#label' src = 'evoque_local_nested.html' # Load a nested template and evoque it t = td.get_template(name, src) self.assertEqual(t.ts, "<h1>%(title)s</h1><p>some %(param)s text</p>")
def test_literals(self): td = Domain(DEFAULT_DIR, restricted=RESTRICTED, errors=ERRORS) name = "template.html" t = td.get_template(name + "#literals") r = "<p>a $ dollar, a literal ${expr}, a % percent... { } ! \ etc.</p>" self.assertEqual(r, t.evoque()) self.assertRaises((SyntaxError,), td.get_template, name+"#unescaped")
def test_overlay_kwargs(self): td = Domain(DEFAULT_DIR) r = "<base>base content!</base>" r_neg = "" responses = [ r, r, r, r, r_neg ] t = td.get_template('overlay_kwargs.html') for i, s in enumerate(t.test()): self.assertEqual(responses[i], s)
def test_overlay_kwargs(self): td = Domain(DEFAULT_DIR) r = "<base>base content!</base>" r_neg = "" responses = [r, r, r, r, r_neg] t = td.get_template('overlay_kwargs.html') for i, s in enumerate(t.test()): self.assertEqual(responses[i], s)
def test_from_string_td(self): td = Domain(DEFAULT_DIR, restricted=RESTRICTED, errors=ERRORS) src = "<h1>${title}</h1><p>some ${param} text</p>" data = dict(title="A Title", param="A Param") r = "<h1>A Title</h1><p>some A Param text</p>" td.set_template("fromstr", src=src, from_string=True) t = td.get_template("fromstr") self.assertEqual(r, t.evoque(**data))
def test_manual_quoting(self): td = Domain(DEFAULT_DIR, restricted=RESTRICTED, errors=ERRORS, quoting="str") name = "template.html#label" t = td.get_template(name) self.failUnless(unistr is t.qsclass) self.failUnless(unistr is t.evoque(title="str", param="<str/>").__class__) from cgi import escape self.assertEqual(self.r_xml_escaped, t.evoque(title="q-xml", param=escape("<in>rm *</in>")))
def test_evoque_kwargs(self): td = Domain(DEFAULT_DIR, restricted=RESTRICTED, errors=4) r = "<h1>TITLE</h1><p>some PARAM text</p>" r_raw = "<h1>${title}</h1><p>some ${param} text</p>" r_q_str = "<h1>TITLE</h1><p>some PARAM text</p>" responses = [ r, r, r, r, r, r_raw, r, r_q_str, r ] t = td.get_template('evoque_kwargs.html') for i, s in enumerate(t.test()): self.assertEqual(responses[i], s)
def test_evoque_raw(self): td = Domain(DEFAULT_DIR, restricted=RESTRICTED, errors=ERRORS) name = 'evoque_local_nested.html#label' r = "<h1>${title}</h1><p>some ${param} text</p>" t = td.get_template(name, raw=True) self.assertEqual([], list(t.test())) self.assertEqual(None, t.ts) self.assertEqual(r, t.evoque(raw=True)) self.assertEqual(r, t.evoque())
def test_typical_usage_via_domain_implied_collection(self): td = Domain(DEFAULT_DIR, restricted=RESTRICTED, errors=ERRORS) name = 'template.html' t = td.get_template(name) self.failUnless(t.collection is td.get_collection()) self.failUnless(t.collection is td.collections[""]) self.failUnless(t is t.collection.get_template(name)) self.failUnless(t is t.collection.domain.get_template(name, collection=t.collection))
def test_file_addressing_collection_root_relative(self): td = Domain(DEFAULT_DIR, restricted=RESTRICTED, errors=ERRORS) name = '/template.html' src = '/template.html' self.assertRaises((LookupError,), td.get_template, name) self.assertRaises((LookupError,), td.get_template, name, src) # can have names start with "/" as long as the c-rel locator does not src = 'template.html' t = td.get_template(name, src=src) self.assertEqual(t.name, name)
def test_parse_locator(self): td = Domain(DEFAULT_DIR, restricted=RESTRICTED, errors=ERRORS) name = "template.html" name_label = "template.html#label" label = "#label" t = td.get_template(name) self.assertEqual(["template.html", None], parse_locator(name)) self.assertEqual(["template.html", "label"], parse_locator(name_label)) self.assertEqual(["", "label"], parse_locator(label)) self.assertRaises((ValueError,), parse_locator, "template.html#label#label")
def evoque(dirname, verbose=False, quoting="xml", restricted=False): DEFAULT_DIR = os.path.join(BASEPATH, 'evoque') name = 'subs.html' from evoque.domain import Domain td = Domain(DEFAULT_DIR, restricted=restricted, errors=4, quoting=quoting) t = td.get_template(name) def render(): return t.evoque(DATA.copy()) if verbose: pr(t.ts, render()) return render
def evoque(dirname, verbose=False, quoting="xml", restricted=False): DEFAULT_DIR = os.path.join(BASEPATH, 'evoque') from evoque.domain import Domain td = Domain(DEFAULT_DIR, restricted=restricted, errors=4, quoting=quoting) t = td.get_template('template.html') t.test() def render(): return t.evoque(DATA.copy()) if verbose: pr(t.ts, render()) return render
def load(self, **args): assert hasattr(self,'name') # can't do "assert self.name" because that throws Attribute error assert hasattr(self,'type') # before assert even gets to it # get the template and call evoque() on it. This should yield a yaml string tf=self.template_file() try: domain=Domain(os.path.dirname(tf), errors=4, quoting=str) # errors=4 means raise errors as an exception except ValueError as ve: raise ConfigError("Error in setting template directory: "+str(ve)) try: tf=self.template_file() template=domain.get_template(tf) except ValueError as ve: raise UserError("%s '%s': missing template file %s" % (self.type, self.name, self.template_file())) vars=args['vars'] if args.has_key('vars') else {} # consider default of self instead of {}? Or is that stupid? vars['config']=RnaseqGlobals.config #print "%s.%s: about to evoque: vars are:\n%s" % (self.name, self.type, yaml.dump(vars)) ev=evoque_dict() if 'vars' in args and args['vars']==None: raise ProgrammerGoof("vars is None") ev.update(vars) #print "templated: ev is %s\nvars is %s" % (ev,vars) try: yaml_str=template.evoque(ev) # why we want to keep this: evoque_dicts protect us against simple Key errors, but not # errors of the type ${readset['missing_key']} except KeyError as ke: print "ke is %s (%s)" % (ke, type(ke)) raise ConfigError("%s '%s': %s" % (self.type, self.name, ke)) except AttributeError as ae: raise ConfigError("%s '%s': %s" % (self.type, self.name, ae)) except TypeError as ae: raise ProgrammerGoof("%s '%s': %s" % (self.type, self.name, ae)) # Check if all keys are needed: if 'final' in args and args['final']: # might be present but false; perl rules! if len(ev.missing_keys)>0: raise ConfigError("%s %s: missing keys in final load: %s" %(self.type, self.name, ", ".join(str(i) for i in (set(ev.missing_keys))))) # call yaml.load on the string produced above, then call self.update() on the resulting dict object # print "yaml_str:\n%s" % yaml_str d=yaml.load(yaml_str) # fixme: what if template isn't yaml??? try: self.update(d) except ProgrammerGoof as oopsie: if (re.search('not a dict or dict_like', str(oopsie))): pass else: raise oopsie return self
def test_evoque_local_nested(self): td = Domain(DEFAULT_DIR, restricted=RESTRICTED, errors=ERRORS) name = 'evoque_local_nested.html' data = dict(title="A Title", param="A Param") r = "<h1>A Title</h1><p>some A Param text</p>" # Load a nested template and evoque it t1 = td.get_template(name + "#label") self.assertEqual(t1.ts, "<h1>%(title)s</h1><p>some %(param)s text</p>") self.assertEqual(r, t1.evoque(**data)) # Load a template that evoques a locally-nested template t2 = td.get_template(name) self.assertEqual(r, t2.evoque(**data))
def test_inline_nested_if(self): td = Domain(DEFAULT_DIR, restricted=RESTRICTED, errors=ERRORS) t = td.get_template('for_seq_items.html') #print t.ts_raw #print t.ts result = """<ul> <li>7:Apples</li> <li>9:789</li> <li class="last">17:Blue</li> </ul> """ self.assertEqual(result, t.evoque())
def test_xml_automatic_quoting(self): if not xml: return td = Domain(DEFAULT_DIR, restricted=RESTRICTED, errors=ERRORS, quoting="xml") name = "template.html#label" t = td.get_template(name) self.failUnless(xml is t.qsclass) self.failUnless(xml is t.evoque(title="xml", param="<xml/>").__class__) self.assertEqual(self.r_xml_escaped, t.evoque(title="q-xml", param="<in>rm *</in>")) r = "<h1>q-xml</h1><p>some <in>rm *</in> text</p>" self.assertEqual(r, t.evoque(title="q-xml", param=xml("<in>rm *</in>")))
def test_extract_test_data(self): td = Domain(DEFAULT_DIR, restricted=RESTRICTED, errors=ERRORS) name = "template.html" t = td.get_template(name) self.assertEqual(t.test_data, [ dict(title="A Title", param="a <param/> for quoting", things=["Apples", 789, "Blue"], something=False, other=False, someexpr='abc', likes_blue=False, flag="Banana", yo="Johnny"), dict(things=[]), dict(something=True), dict(something=False, other=True), dict(other=False, likes_blue=True) ])
def evoque_mq(dirname, verbose=False): DEFAULT_DIR = os.path.join(BASEPATH, 'evoque') name = 'subs_mq.html' from evoque.domain import Domain td = Domain(DEFAULT_DIR, restricted=False, quoting="str") import cgi td.set_on_globals("quote", cgi.escape) t = td.get_template(name) def render(): return t.evoque(DATA.copy()) if verbose: pr(t.ts, render()) return render
def evoque_mq(dirname, verbose=False): DEFAULT_DIR = os.path.join(BASEPATH, 'evoque') from evoque.domain import Domain td = Domain(DEFAULT_DIR, restricted=False, quoting="str") import cgi td.set_on_globals("quote", cgi.escape) t = td.get_template('template_mq.html') t.test() def render(): return t.evoque(DATA.copy()) if verbose: pr(t.ts, render()) return render
def test_unsafe_file_expressions(self): # Create a new domain for this, to be able to run with a different # errors setting td = Domain(DEFAULT_DIR, restricted=True, errors=2, quoting="str") name = 'restricted_exprs.txt' t = td.get_template(name) result = """ [EvalError(().__class__.mro()[1].__subclasses__())] ().__class__.mro()[1].__subclasses__() ().__class__.mro()[1].__subclasses__() [EvalError(eval(expr))] [EvalError(evoque("test", src="${"+expr+"}", from_string=True))] """ self.assertEqual(result, t.evoque())
def evoque_template(template, vars, *more_vars, **kw_vars): domain=Domain(os.getcwd(), errors=4) # we actually don't care about the first arg domain.set_template('template', src=template) tmp=domain.get_template('template') cvars=vars.copy() for v in more_vars: try: cvars.update(v) except Exception as e: print "caught %s" % e for k,v in kw_vars.items(): cvars[k]=kw_vars[k] return tmp.evoque(cvars)
def test_expr_formatting(self): td = Domain(DEFAULT_DIR, restricted=RESTRICTED, errors=ERRORS) data = dict(amount=1.0/3) src = "${amount!.4f}" td.set_template("t1", src=src, from_string=True) self.assertEqual("0.3333", td.get_template("t1").evoque(**data)) src = "${ amount ! .3f }" td.set_template("t2", src=src, from_string=True) self.assertEqual("0.333", td.get_template("t2").evoque(**data))
def as_python(self): template_filename=self.rnaseq.globals['step_template'] try: domain=self.rnaseq.globals['domain'] except: domain=os.getcwd() t=Domain(domain).get_template(template_filename) # step.template needs: name, input, output, pipeline_var_name # fixme: we killed input_str(), etc, (not cmd_str(), tho) vars={'input':self.flatten_attr('inputs'), 'output':self.flatten_attr('outputs'), 'name':self.name, 'pipeline_var_name':self.pipeline_var_name, } template=t.evoque(vars) return template
def set_domain(self): default_dir = abspath(join(dirname(__file__), 'evoque')) # create template domain instance # here restating all defaults, for doc convenience self.domain = Domain(default_dir, restricted=False, errors=3, log=logging.getLogger("evoque"), cache_size=0, auto_reload=60, slurpy_directives=True, quoting="xml", input_encoding="utf-8", filters=[]) # extensions to global namespace self.domain.set_on_globals("pformat", pformat) # preload a default template, e.g. for error pages self.domain.get_collection().get_template("", "base.html")
class SitePublisher(Publisher): configuration = dict( http_address=('', 8001), as_https_address=('localhost', 9001), https_address=('localhost', 10001), scgi_address=('localhost', 11001), ) def __init__(self, **kwargs): super(SitePublisher, self).__init__(**kwargs) self.set_domain() def set_domain(self): default_dir = abspath(join(dirname(__file__), 'evoque')) # create template domain instance # here restating all defaults, for doc convenience self.domain = Domain(default_dir, restricted=False, errors=3, log=logging.getLogger("evoque"), cache_size=0, auto_reload=60, slurpy_directives=True, quoting="xml", input_encoding="utf-8", filters=[]) # extensions to global namespace self.domain.set_on_globals("pformat", pformat) # preload a default template, e.g. for error pages self.domain.get_collection().get_template("", "base.html") # other setup e.g. adding other collections, template aliases # see: http://evoque.gizmojo.org/usage/ def page(self, title, *content, **kwargs): """(title, *content, **kwargs) -> qpy.xml Return a page formatted according to the site-standard. """ # we make use of only the "template" kwarg -- there are # other possibilities, see: domain.get_template() template = kwargs.get("template", "") return self.domain.get_template(template).evoque(title=title, content=content, **kwargs)
def write_starflow_script(pipeline, globals, sample): domain=globals['domain'] d=Domain(domain) t=d.get_template(globals['starflow_template']) # build the rest of the variables: vars={'working_dir':sample.working_dir(), 'org':sample.org, } vars.update(globals) starflow_script=t.evoque(vars) # write script: fn=pipeline.script_filename('starflow/Temp','go','py') f=open(fn, 'w') f.write(starflow_script) f.close print "%s written" % fn return fn
def setup_domain(): import logging domain = Domain( # root folder for the default template collection, must be abspath "/tmp", # whether evaluation namespace is restricted or not restricted=True, # how should any evaluation errors be rendered # int 0 to 4, for: [silent, zero, name, render, raise] errors=3, # domain logger; additional settings should be specified via the # app's config ini file, just as for any other logger. E.g: # [logger_notifications] # level = DEBUG # handlers = # qualname = notifications log=logging.getLogger("notifications"), # [collections] int, max loaded templates in a collection cache_size=0, # [collections] int, min seconds to wait between checks for # whether a template needs reloading auto_reload=0, # [collections] bool, consume all whitespace trailing a directive slurpy_directives=True, # [collections/templates] str or class, to specify the *escaped* # string class that should be used i.e. if any str input is not of # this type, then cast it to this type). # Builtin str key values are: "xml" -> qpy.xml, "str" -> unicode quoting="str", # [collections/templates] str, preferred encoding to be tried # first when decoding template source. Evoque decodes template # strings heuristically, i.e. guesses the input encoding. input_encoding="utf-8", # [collections/templates] list of filter functions, each having # the following signature: filter_func(s:basestring) -> basestring # The functions will be called, in a left-to-right order, after # template is rendered. NOTE: not settable from the conf ini. filters=[] ) # add "site" settings on globals domain.set_on_globals("site", TemplateNamespaceSite()) return domain
def test_overlay(self): td = Domain(DEFAULT_DIR) t = td.get_template('overlay.html') self.assertEqual(eval("dict(%s)" % (t.eval_overlay)), dict(name="base.html")) space, overlay = t.get_space_overlay() self.assertTrue(space is True) self.assertTrue(t.labels == ["content"]) # t.evoque(title="positive overlay test", parametrized="and happy") chain_pos = td.get_template('overlay_chain_pos.html') self.assertEqual(eval("dict(%s)" % (chain_pos.eval_overlay)), dict(name="overlay_mid.html")) space, overlay = chain_pos.get_space_overlay() self.assertTrue(space is True) self.assertTrue(chain_pos.labels == ["content"]) # chain_pos.evoque(title="positive overlay test", parametrized="and happy") chain_neg = td.get_template('overlay_chain_neg.html') self.assertEqual(eval("dict(%s)" % (chain_neg.eval_overlay)), dict(name="overlay_mid.html", space="negative")) space, overlay = chain_neg.get_space_overlay() self.assertTrue(space is False) self.assertTrue(chain_neg.labels == ["content", "footer"]) # chain_neg.evoque(title="negative overlay test", parametrized="and happy") b = td.get_template('base.html') self.assertTrue(b.labels == ["header", "content", "footer"]) self.assertFalse(b.eval_overlay is not None) self.assertRaises((TypeError, ), b.get_space_overlay)
def test_raw_nested(self): if not xml: return td = Domain(DEFAULT_DIR, restricted=RESTRICTED, errors=ERRORS) t = td.get_template('raw_nested.html') self.assertEqual(t.evoque()[:87], """ $begin{table_row} $for{ col in row } <td>${col}</td> $else""") self.failUnless(isinstance(t.evoque(), xml)) # template #snapshot is already loaded with raw=True, quoting=str snap = td.get_template('raw_nested.html#snapshot') self.failUnless(snap.raw) self.failUnless(snap.qsclass is unistr) self.failUnless(isinstance(snap.evoque(), unistr)) # template #snapshot is still already loaded... snapx = td.get_template('raw_nested.html#snapshot_xml') self.failUnless(isinstance(snapx.evoque(), xml)) self.failUnless(snap.qsclass is unistr) self.failUnless(isinstance(snap.evoque(), unistr)) snap.unload() self.failUnless(isinstance(snapx.evoque(), xml)) # reloads #snapshot snap = td.get_template('raw_nested.html#snapshot') self.failUnless(snap.qsclass is xml) self.failUnless(isinstance(snap.evoque(raw=True), xml))
def test_evoque_local_nested_from_string(self): td = Domain(DEFAULT_DIR, restricted=RESTRICTED, errors=ERRORS) src = open(join(DEFAULT_DIR, "evoque_local_nested.html")).read() name = "fromstr" nested_name = name + "#label" data = dict(title="A Title", param="A Param") r = "<h1>A Title</h1><p>some A Param text</p>" # Load a from_string template that locally-nests another template td.set_template(name, src=src, from_string=True) t1 = td.get_template(name) # Verify nested template is not yet loaded self.assertEqual(False, t1.collection.has_template(nested_name)) # Evoque, and verify response (multiple times, ensure data stays ok) self.assertEqual(r, t1.evoque(data)) # data as locals self.assertEqual(r, t1.evoque(**data)) # data as kw self.assertEqual(r, t1.evoque(data)) # data as locals self.assertEqual(r, t1.evoque(**data)) # data as kw # Verify nested template is now loaded self.assertEqual(True, t1.collection.has_template(nested_name)) # Verify that tring to set nested template will fail self.assertRaises((ValueError,), td.set_template, nested_name, src=src, from_string=True) t2 = td.get_template(nested_name) self.assertEqual(t2.ts, "<h1>%(title)s</h1><p>some %(param)s text</p>") self.assertEqual(r, t2.evoque(**data))
def test_overlay_naming_schemes_separate_files(self): domain = Domain(DEFAULT_DIR) t0 = domain.get_template("overlay_naming_base.html") self.assertEqual(t0.evoque(), "<base>base content!</base>") t1 = domain.get_template("overlay_naming_1.html") self.assertEqual(t1.evoque(), "<base><m1>literal unquoted</m1></base>") t2 = domain.get_template("overlay_naming_2.html") self.assertEqual(t2.evoque(), "<base><m2>literal quoted</m2></base>") t3 = domain.get_template("overlay_naming_3.html") self.assertEqual(t3.evoque(site_template="overlay_naming_base.html"), "<base><m3>kw unquoted</m3></base>") t4 = domain.get_template("overlay_naming_4.html") self.assertEqual(t4.evoque(), "<base><m4>kw quoted</m4></base>")
def evoque(verbose=False, quoting="xml", restricted=False, template_string=None): from evoque.domain import Domain DEFAULT_DIR = os.path.join(BASEDIR, 'evoque') td = Domain(DEFAULT_DIR, restricted=restricted, errors=4, quoting=quoting) if template_string is None: # $begin{evoque_template} template_string = """<table> $for{ row in table } <tr>$for{ col in row }<td>${col}</td>$rof</tr> $rof </table> $test{ table=[("a","b","c","d","<escape-me/>","f","g","h","i","j")] } """ # $end{evoque_template} td.set_template("bigtable", src=template_string, quoting=quoting) t = td.get_template("bigtable") t.test() def render(): return t.evoque({'table':TABLE_DATA}) if verbose: #open("/tmp/evoque_bench_bigtable_evoque.html", "w").write(render()) pr(t.ts) pr('--------------------------------------------------------') pr(render()[:300] + "...") return render
def test_prefer(self): td = Domain(DEFAULT_DIR, restricted=RESTRICTED, errors=ERRORS) t = td.get_template('raw_nested.html') self.assertEqual(t.prefer, dict(raw=False, quoting="xml")) def upper(s): return s.upper() td.set_on_globals("upper", upper) p = td.get_template('raw_nested.html#preferences') self.assertEqual(p.raw, True) self.assertEqual(p.qsclass, unistr)
def test_prefer_with_overrides(self): td = Domain(DEFAULT_DIR, restricted=RESTRICTED, errors=ERRORS) def upper(s): return s.upper() def trim(s): return s.strip() td.set_on_globals("upper", upper) td.set_on_globals("trim", upper) p = td.get_template('raw_nested.html#preferences', raw=False, filters=[trim, upper]) self.assertEqual(p.raw, False) self.assertEqual(p.qsclass, unistr) r = 'SHOULD REFRESH [QUOTING: NONE OR !="STR"] WHEN TEMPLATE IS LOADED' self.assertEqual(r, p.evoque()) r = 'SHOULD REFRESH [QUOTING: NONE OR !="STR"] WHEN CHANGED TEMPLATE IS LOADED' self.assertEqual(r, p.evoque(what="changed template"))
def test_dynamic_site_template(self): domain = Domain(DEFAULT_DIR) # # by reset s = domain.get_template("SITE-TEMPLATE", src="site_template_table.html") t = domain.get_template("site_dyn_page.html") r_table = t.evoque(title="hey tabby!", message="you're kinda square!", footer="you reckon?") self.assertTrue(r_table == """<html> <head><title>site-table: hey tabby!</title></head> <body> <table class="layout"> <tr><th>site-table: <h1>hey tabby!</h1></th></tr> <tr><td>page: you're kinda square!</td></tr> <tr><td>site-table: you reckon?</td></tr> </table> </body> </html> """) s.unload() s = domain.get_template("SITE-TEMPLATE", src="site_template_divs.html") r_divs = t.evoque(title="howdie!", message="ya bin free floatin' good?", footer="sure thang!") self.assertTrue(r_divs == """<html> <head><title>site-div: howdie!</title></head> <body> <div class="layout"> <div class="header">site-div: <h1>howdie!</h1></div> <div class="content">page: ya bin free floatin' good?</div> <div class="footer">site-div: sure thang!</div> </div> </body> </html> """) # by parameter t = domain.get_template("site_dyn_page_var.html") self.assertEqual( r_table, t.evoque(my_site_theme="site_template_table.html", title="hey tabby!", message="you're kinda square!", footer="you reckon?")) self.assertEqual( r_divs, t.evoque(my_site_theme="site_template_divs.html", title="howdie!", message="ya bin free floatin' good?", footer="sure thang!"))
def __init__( self, domain, name, path, # defaults from Domain cache_size=None, auto_reload=None, slurpy_directives=None, # defaults (from Domain) for Templates quoting=None, input_encoding=None, filters=None): """ domain: either(None, Domain) name: str, name by which to retrieve the collection path: str, abs path for root folder for the collection For more on defaults from Domain init parameters, see the docstring in domain.Domain.__init__(). Preferred way to create a new collection: domain.set_collection() """ # $end{init} check_dir(path) self.dir = normpath(path) if name is None: raise ValueError("A Collection cannot have a None name") self.name = name domain_kw = specified_kwargs(self.from_domain, vars()) if domain is None: # in this case self is the default_collection from evoque.domain import Domain domain = Domain(self, **domain_kw) self.domain = domain # defaults -- cascaded down from domain for attr in self.from_domain: setattr(self, attr, domain_kw.get(attr, getattr(domain, attr))) # self.cache = Cache(maxsize=self.cache_size) self.translator = Translator(self)