Just for fun....
import re
R=re.compile('^[\w\-\:]+')
def parse(text,context = None):
context = context or {}
stack = []
for line in text.split('\n')+['%END']:
if not line: continue
is_tag = False
tag = 'div'
classes = []
ids = []
attributes = {}
value = ''
spaces = len(line)-len(line.lstrip())
line = line.strip()
i = 0
while i < len(line):
x = line[i]
if x=='%':
is_tag = True
tag = R.match(line[i+1:]).group()
i+=1+len(tag)
elif x=='#':
is_tag = True
id = R.match(line[i+1:]).group()
ids.append(id)
i+=1+len(id)
elif x=='.':
is_tag = True
c = R.match(line[i+1:]).group()
classes.append(c)
i+=1+len(c)
elif x=='[':
j = line[i+1:].find(']')+i+1
attrs = line[i+1:j]
if attrs:
for item in attrs.split(','):
k,v = item.split('=')
attributes[k] = eval(v,context)
i = j+1
elif x=='=':
value = str(eval(line[i+1:].strip(),context))
break
else:
value = line[i:].strip()
break
if classes:
attributes['class']=' '.join(classes)
if ids:
attributes['id']=' '.join(ids)
if is_tag or tag=='END':
while stack and stack[-1][0]>=spaces:
print (' '*stack[-1][0]) + '</%s>' % stack[-1][1]
del stack[-1]
if not tag in ('img','link','input'):
stack.append((spaces,tag))
attrs = (attributes and ' ' + \
' '.join('%s="%s"' % (k,v) \
for k,v in attributes.items())
or '')
if not tag=='END':
s = ' '*spaces
if value:
print '%s<%s%s>\n%s%s' % (s, tag, attrs, s+' ',
value)
elif tag in ('img','link','input'):
print '%s<%s%s />' % (s, tag, attrs)
else:
print '%s<%s%s>' % (s, tag, attrs)
else:
print value
parse("""
#wrapper
.header[name="test",id=a] Title
text
.body
.main Text for the
body
%img[src="http:example.com"]
%p=2+4
""", dict(a="test"))
OUTPUT
<div id="wrapper">
<div class="header" name="test" id="test">
Title text
</div>
<div class="body">
<div class="main">
Text for the body
</div>
<img src="http:example.com" />
<p>
6
</p>
</div>
</div>
It principle it would not be difficult to include this in the web2py
template language and simply allow {{...}} in there and then parse it
as regular web2py template.
In principle we could modify the web2py template language and modify
the code I just posted to allow
On Dec 20, 10:30 am, Ross Peoples <[email protected]> wrote:
> That's funny :) I didn't go very deep into the haml docs. I just saw the
> part about:
>
> #wrapper
> .header Title text
> .body Text for the body
>
> And realized it would be quicker to write than:
>
> <div id="wrapper">
> <div class="header">Title text</div>
> <div class="body">Text for the body</div>
> </div>
>
> Wonder if we could do something like this in web2py, but make it suit our
> needs while making it faster to write than HTML.
>
>
>
>
>
>
>
> On Tuesday, December 20, 2011 10:43:36 AM UTC-5, Massimo Di Pierro wrote:
>
> > so ... ruby has discovered the value of whitespaces... but in the
> > wrong place!.