diff --git a/hyde/ext/templates/jinja.py b/hyde/ext/templates/jinja.py index ed8e83b..bfe2d1b 100644 --- a/hyde/ext/templates/jinja.py +++ b/hyde/ext/templates/jinja.py @@ -62,7 +62,6 @@ def markdown(env, value): md = markdown.Markdown(**d) return md.convert(output) - @environmentfilter def syntax(env, value, lexer=None, filename=None): """ @@ -117,6 +116,49 @@ class Markdown(Extension): output = caller().strip() return markdown(self.environment, output) +class YamlVar(Extension): + """ + An extension that converts the content between the tags + into an yaml object and sets the value in the given + variable. + """ + + tags = set(['yaml']) + + def parse(self, parser): + """ + Parses the contained data and defers to the callback to load it as + yaml. + """ + lineno = parser.stream.next().lineno + var = parser.stream.expect('name').value + body = parser.parse_statements(['name:endyaml'], drop_needle=True) + return [ + nodes.Assign( + nodes.Name(var, 'store'), + nodes.Const({}) + ).set_lineno(lineno), + nodes.CallBlock( + self.call_method('_set_yaml', args=[nodes.Name(var, 'load')]), + [], [], body).set_lineno(lineno) + ] + + + def _set_yaml(self, var, caller=None): + """ + Loads the yaml data into the specified variable. + """ + if not caller: + return '' + try: + import yaml + except ImportError: + return '' + + out = caller().strip() + var.update(yaml.load(out)) + return '' + def parse_kwargs(parser): name = parser.stream.expect('name').value parser.stream.expect('assign') @@ -388,6 +430,7 @@ class Jinja2Template(Template): Syntax, Reference, Refer, + YamlVar, 'jinja2.ext.do', 'jinja2.ext.loopcontrols', 'jinja2.ext.with_']) diff --git a/hyde/tests/test_jinja2template.py b/hyde/tests/test_jinja2template.py index 652cfff..98eb1b5 100644 --- a/hyde/tests/test_jinja2template.py +++ b/hyde/tests/test_jinja2template.py @@ -387,4 +387,45 @@ Hyde & Jinja. """ html = assert_markdown_typogrify_processed_well(text, text2) assert "mark" not in html - assert "reference" not in html \ No newline at end of file + assert "reference" not in html + + + def test_yaml_tag(salf): + + text = """ +{% yaml test %} +one: + - A + - B + - C +two: + - D + - E + - F +{% endyaml %} +{% for section, values in test.items() %} + +{% endfor %} +""" + t = Jinja2Template(JINJA2.path) + t.configure(None) + html = t.render(text, {}).strip() + actual = PyQuery(html) + assert actual("ul").length == 2 + assert actual("ul.one").length == 1 + assert actual("ul.two").length == 1 + + assert actual("li").length == 6 + + assert actual("ul.one li").length == 3 + assert actual("ul.two li").length == 3 + + ones = [item.text for item in actual("ul.one li")] + assert ones == ["A", "B", "C"] + + twos = [item.text for item in actual("ul.two li")] + assert twos == ["D", "E", "F"] \ No newline at end of file