Expanding Albatross Macros in custom tags
When writing custom tags, it is often required that the contents of the tag also be searched for Albatross tags, This allows things like <al-value ...> calls inside the contents or arguments of the tag.
This is easily done using the Template class like so:
1 # A silly test tag that does nothing sensible
2 class MyTag(EmptyTag):
3 def __init__(self, ctx, filename, line_num, attribs):
4 EmptyTag.__init__(self, ctx, filename, line_num, attribs)
5 self.str = 'A long string containing <al-value expr="name"> albatross tags.'
6
7 def to_html(self, ctx):
8 ctx.write_content('Some HTML at the start of the tag')
9 Template(ctx, '<magic>', self.str).to_html(ctx) # Expand all the Albatross macros in self.str
10 ctx.write_content('Some HTML at the end of the tag')
Another, similar, case might be that you need to expand a tag or a macro without necessarily sending the resulting HTML to the application. You can use the ApplicationContext push_context_trap() and pop_context_trap() functions, like so:
1 # Another silly tag that does nothing sensible
2 class SafeHref(albatross.Href):
3 def to_html(self, ctx)
4 ctx.push_content_trap()
5 albatross.Href.to_html(self, ctx)
6 html = ctx.pop_content_trap()
7 # html contains the HTML representation, but it hasn't been send to the browser
8 if html.lower().find('sex'):
9 ctx.write_content('Inappropriate URL removed')
10 else:
11 ctx.write_content(html)