Apr182008
Breve's Macro Madness
Filed under: breveContinuing my tradition of abusing whatever language is under my keyboard (and in the interest of stress-testing Breve), here's a template that traverses its own DOM and extracts out CSS selectors:
assign ( '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 ( 'walk_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 Breve!" ]
]
), walk_results ( selectors ) ]
]
This outputs the original page with the CSS selectors at the end like so:
<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 Breve!</span>
</div>
<pre>
div.text { }
div#main-content { }
span.bold { }
</pre>
</body>
</html>
Don't try this at home, professional driver on closed-course, etc.
Also, this requires Breve 1.2.1 or greater (it required Tag.walk to be changed to return self rather than None).



