This is a really ugly example concocted to show the power of macros. Don't try this at home, let alone in a work-related environment.
This is a template that traverses itself using macros and Tag.walk. It finds all tags with id or class attributes set and stores them in a list for later retrieval.
let ( selectors = [ ] ),
macro ( 'get_selectors', lambda tag, is_tag: (
macro ( 'css_sep', lambda attr:
'.' if attr == 'class' else '#'
),
selectors.extend ( [
"%s%s%s { }" % ( tag.name, css_sep ( _k.strip ( '_' ) ), _v )
for _k, _v in tag.attrs.items ( )
if _k.strip ( '_' ) in ( 'id', 'class' )
] )
) ),
macro ( 'walk_dom', lambda tag:
tag.walk ( get_selectors, True ) and tag
),
macro ( 'output_results', lambda selectors:
pre [ '\n'.join ( selectors ) ]
),
html [
head [ title [ 'macro madness' ] ],
body [ walk_dom (
div ( class_='text', id='main-content' ) [
img ( src='/images/breve-logo.png', alt='breve logo' ),
br,
span ( class_='bold' ) [ "Hello from Brevé!" ]
]
), output_results ( selectors ) ]
]
The above outputs the original template with potential CSS selectors appended to the end:
<?xml version="1.0" encoding="UTF-8"?>
<html>
<head>
<title>macro madness</title>
</head>
<body>
<div class="text" id="main-content">
<img src="/images/breve-logo.png" alt="breve logo"></img>
<br />
<span class="bold">Hello from Brevé!</span>
</div>
<pre>
div.text { }
div#main-content { }
span.bold { }
</pre>
</body>
</html>
I'd like to remind you that this template spits in the face of everything Brevé holds dear and is only provided as an example of the power of macros.