Skip to content
Snippets Groups Projects
Commit b7eaf474 authored by Mike Bayer's avatar Mike Bayer
Browse files

docs, capturing, etc

parent 9127d38a
No related branches found
No related tags found
No related merge requests found
Defs
=============
The def is the single tag used to demarcate any block of text and/or code. It exists within generated Python as a callable function.
<%def name="hello">
hello world
</%def>
They are normally called as expressions.
the def: ${hello()}
If the `<%def>` is not nested inside of another `<%def>`, its known as a top level def and can be accessed anywhere in the template, including above where it was defined.
All defs, top level or not, have access to the current contextual namespace in exactly the same way their parent template does. Suppose the template below is executed with the variables `username` and `accountdata` inside the context:
Hello there ${username}, how are ya. Lets see what your account says:
${account()}
<%def name="account">
Account for ${username}:<br/>
% for row in accountdata:
Value: ${row}<br/>
% endfor
</%def>
Since defs are just Python functions, you can define and pass arguments to them as well:
${account(name='john')}
<%def name="account(accountname, type='regular')">
account name: ${accountname}, type ${type}
</%def>
When you declare an argument signature for your def, they are required following normal Python conventions (i.e., all arguments are required except keyword arguments with a default value). This is in contrast to using context-level variables, which evaluate to `UNDEFINED` if you reference a name that does not exist.
#### Calling defs from Other Files {@name=remotedefs}
Top level `<%defs>` are **exported** by your template's module, and can be called from the outside; including from other templates, as well as normal Python code. Calling a `<%def>` from another template is something like using an `<%include>` - except you are calling a specific function within the template, not the whole template.
Calling a remote def is a little like calling other modules in Python. There is an "import" step to pull the names from another template into your own template; then the function or functions are available.
To import another template, use the `<%namespace>` tag:
<%namespace name="mystuff" file="mystuff.html"/>
The namespace tag is declared once per template, and adds a local variable "mystuff" to the current scope.
Then, just call the defs off of `mystuff`:
${mystuff.somedef(x=5,y=7)}
The `<%namespace>` tag also supports some of the other semantics of Python's `import` statement, including pulling names into the local variable space, or using `*` to represent all names:
<%namespace file="mystuff.html" import="account, printtotal"/>
your account is: ${account()}
your total is ${printtotal()}
As you might guess from the above code, the callables that you import also get access to the current context (the callables imported from the namespace are generated in the scope of the current context).
Heres an example using `*`:
<%namespace file="otherstuff.html" import="*"/>
${callsomething('test')}
#### Defs within Defs {@name=nesteddefs}
The def model follows regular Python rules for closures. Declaring `<%def>` inside another `<%def>` declares it within the parent's **enclosing scope**:
<%def name="mydef">
<%def name="subdef">
a sub def
</%def>
im the def, and the subcomopnent is ${subdef()}
</%def>
Just like Python, names that exist outside the inner `<%def>` exist inside it as well:
<%
x = 12
%>
<%def name="outer">
<%
y = 15
%>
<%def name="inner">
inner, x is ${x}, y is ${y}
</%def>
outer, x is ${x}, y is ${y}
</%def>
Assigning to a name inside of a def declares that name as local to the scope of that def (again, like Python itself). This means the following code will raise an error:
<%
x = 10
%>
<%def name="somedef">
# error !
somedef, x is ${x}
<%
x = 27
%>
</%def>
...because the assignment to `x` declares x as local to the scope of `somedef`, rendering the "outer" version unreachable in the expression that tries to render it.
#### Calling a def with embedded content and/or other defs {@name=defswithcontent}
A flip-side to def within def is a def call with content. This is where you call a def, and at the same time declare a block of content (or multiple blocks) that can be used by the def being called. To achieve this, the target def is invoked using the `<%call>` tag instead of the normal `${}` syntax. The target def then gets a variable `caller` placed in its context which contains references to the body of the `<%call>` tag. The default body of the tag is available via the name `body`:
<%def name="buildtable">
<table>
<tr><td>
${caller.body()}
</td></tr>
</table>
</%def>
<%call expr="buildtable">
I am the table body.
</%call>
This produces the output:
<table>
<tr><td>
I am the table body.
</td></tr>
</table>
The `body` name is executed each time its referenced. This means you can use def-call-with-content to build iterators, conditionals, etc:
<%def name="lister(count)">
% for x in range(1,count):
${caller.body()}
% endfor
</%def>
<%call expr="lister(3)">
hi
</%call>
Produces:
hi
hi
hi
A custom "conditional" tag:
<%def name="conditional(expr)">
% if expr:
${body()}
%
</%def>
<%call expr="conditional(4==4)">
im the result
</%call>
Produces:
im the result
But that's not all. The `body()` function also can handle arguments, which will augment the local namespace of the body callable:
<%def name="layoutdata(somedata)">
<table>
% for item in somedata:
<tr>
% for col in item:
<td>${body(col=col)}</td>\
% endfor
</tr>
% endfor
</table>
</%def>
<%call expr="layoutdata([[1,2,3],[4,5,6],[7,8,9]])">
Body data: ${col}
</%call>
Produces:
<table>
<tr>
<td>Body data: 1</td><td>Body data: 2</td><td>Body data: 3</td>
<td>Body data: 2</td><td>Body data: 5</td><td>Body data: 6</td>
<td>Body data: 3</td><td>Body data: 8</td><td>Body data: 9</td>
</tr>
</table>
You don't have to stick to calling just the `body()` function. The caller can define any number of callables, allowing the `<%call>` tag to produce whole layouts:
<%def name="layout">
# a layout def
<div class="mainlayout">
<div class="header">
${caller.header()}
</div>
<div class="sidebar">
${caller.sidebar()}
</div>
<div class="content">
${caller.body()}
</div>
</div>
</%def>
# calls the layout def
<%call expr="layout">
<%def name="header">
I am the header
</%def>
<%def name="sidebar">
<ul>
<li>sidebar 1</li>
<li>sidebar 2</li>
</ul>
</%def>
this is the body
</%call>
The above layout would produce:
<div class="mainlayout">
<div class="header">
I am the header
</div>
<div class="sidebar">
<ul>
<li>sidebar 1</li>
<li>sidebar 2</li>
</ul>
</div>
<div class="content">
this is the body
</div>
</div>
......@@ -10,6 +10,7 @@ import read_markdown, toc
files = [
'index',
'defs',
'namespaces',
'caching',
]
......@@ -38,12 +39,7 @@ def genfile(name, toc):
outfile.write(lookup.get_template(infile).render(toc=toc, extension='html'))
for filename in files:
try:
genfile(filename, root)
except Exception, e:
import mako.exceptions
print mako.exceptions.get_error_template().render(error=e)
break
genfile(filename, root)
......
......@@ -20,25 +20,20 @@
if item is None:
raise "path: " + path
%>
<A name="${item.path}"></a>
<div class="subsection" style="margin-left:${repr(item.depth * 10)}px;">
<%
content = caller.body()
content = capture(caller.body)
re2 = re.compile(r"'''PYESC(.+?)PYESC'''", re.S)
content = re2.sub(lambda m: m.group(1), content)
%>
% if item.depth > 1:
<h3>${description or item.description}</h3>
% endif
<div class="sectiontext">
${content}
</div>
% if item.depth > 1:
% if (item.next and item.next.depth >= item.depth):
<a href="#${ item.get_page_root().path }" class="toclink">back to section top</a>
......@@ -58,7 +53,7 @@
<%def name="codeline" filter="trim,h">
<span class="codeline">${ m.content() }</span>
<span class="codeline">${ caller.body() }</span>
</%def>
<%def name="code(title=None, syntaxtype='python', html_escape=False, use_sliders=False)">
......
......@@ -105,7 +105,7 @@ def text_error_template(lookup=None):
import mako.template
return mako.template.Template(r"""
<%!
from mako.exceptions import rich_traceback
from mako.exceptions import RichTraceback
%>
Error !
<%
......
......@@ -224,8 +224,10 @@ class IncludeTag(Tag):
class NamespaceTag(Tag):
__keyword__ = 'namespace'
def __init__(self, keyword, attributes, **kwargs):
super(NamespaceTag, self).__init__(keyword, attributes, (), ('name','inheritable','file','import'), ('name',), **kwargs)
self.name = attributes['name']
super(NamespaceTag, self).__init__(keyword, attributes, (), ('name','inheritable','file','import'), (), **kwargs)
self.name = attributes.get('name', '__anon_%s' % hex(id(self)))
if not 'name' in attributes and not 'import' in attributes:
raise exceptions.CompileException("'name' and/or 'import' attributes are required for <%namespace>", self.lineno, self.pos, self.filename)
def declared_identifiers(self):
return []
......
......@@ -147,6 +147,8 @@ class Namespace(object):
def capture(context, callable_, *args, **kwargs):
"""execute the given template def, capturing the output into a buffer."""
if not callable(callable_):
raise exceptions.RuntimeException("capture() function expects a callable as its argument (i.e. capture(func, *args, **kwargs))")
context.push_buffer()
try:
callable_(*args, **kwargs)
......
......@@ -67,6 +67,21 @@ class BufferTest(unittest.TestCase):
""")
assert flatten_result(t.render()) == "hi-> this is foo <-hi"
def test_capture_ccall(self):
t = Template("""
<%def name="foo">
<%
x = capture(caller.body)
%>
this is foo. body: ${x}
</%def>
<%call expr="foo()">
ccall body
</%call>
""")
print t.render()
if __name__ == '__main__':
unittest.main()
\ No newline at end of file
......@@ -43,6 +43,30 @@ class NamespaceTest(unittest.TestCase):
assert flatten_result(collection.get_template('main.html').render()) == "this is main. def1: hi def2: there"
def test_context(self):
"""test that namespace callables get access to the current context"""
collection = lookup.TemplateLookup()
collection.put_string('main.html', """
<%namespace name="comp" file="defs.html"/>
this is main. ${comp.def1()}
${comp.def2("there")}
""")
collection.put_string('defs.html', """
<%def name="def1">
def1: x is ${x}
</%def>
<%def name="def2(x)">
def2: x is ${x}
</%def>
""")
print collection.get_template('main.html').render(x="context x")
assert flatten_result(collection.get_template('main.html').render(x="context x")) == "this is main. def1: x is context x def2: x is there"
def test_overload(self):
collection = lookup.TemplateLookup()
......@@ -246,8 +270,8 @@ class NamespaceTest(unittest.TestCase):
</%def>
""")
collection.put_string("index.html", """
<%namespace name="func" file="functions.html" import="*"/>
<%namespace name="func2" file="func2.html" import="a, b"/>
<%namespace file="functions.html" import="*"/>
<%namespace file="func2.html" import="a, b"/>
${foo()}
${bar()}
${lala()}
......@@ -255,6 +279,7 @@ class NamespaceTest(unittest.TestCase):
${b()}
${x}
""")
print collection.get_template('index.html').code
assert result_lines(collection.get_template("index.html").render(bar="this is bar", x="this is x")) == [
"this is foo",
"this is bar",
......@@ -277,7 +302,7 @@ class NamespaceTest(unittest.TestCase):
""")
collection.put_string("index.html", """
<%namespace name="func" file="functions.html" import="*"/>
<%namespace file="functions.html" import="*"/>
<%def name="cl1">
${foo()}
</%def>
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment