Browse Source

Added yaml extension for inline yaml in templates

main
Lakshmi Vyasarajan 14 years ago
parent
commit
88b701b813
2 changed files with 86 additions and 2 deletions
  1. +44
    -1
      hyde/ext/templates/jinja.py
  2. +42
    -1
      hyde/tests/test_jinja2template.py

+ 44
- 1
hyde/ext/templates/jinja.py View File

@@ -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_'])


+ 42
- 1
hyde/tests/test_jinja2template.py View File

@@ -387,4 +387,45 @@ Hyde & Jinja.
"""
html = assert_markdown_typogrify_processed_well(text, text2)
assert "mark" not in html
assert "reference" not in html
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() %}
<ul class="{{ section }}">
{% for value in values %}
<li>{{ value }}</li>
{% endfor %}
</ul>
{% 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"]

Loading…
Cancel
Save