Skip to content

Commit 58d2511

Browse files
author
Barry Coughlan
committed
Basic multiline HAML support using neoascetic example from #38
1 parent 3d5c47c commit 58d2511

File tree

2 files changed

+47
-3
lines changed

2 files changed

+47
-3
lines changed

hamlpy/attribute_dict_parser.py

+27-3
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,12 @@
11
import re
2+
import hamlpy
23

34
# Valid characters for dictionary key
45
re_key = re.compile(r'[a-zA-Z0-9-_]+')
56
re_nums = re.compile(r'[0-9\.]+')
6-
7+
re_whitespace = re.compile(r'([ \t]+)')
8+
re_leading_spaces = re.compile(r'^\s+', re.MULTILINE)
9+
re_line = re.compile(r'.*')
710
re_sq= re.compile(r'(.*?)(?<!\\)(?:\')')
811
re_dq= re.compile(r'(.*?)(?<!\\)(?:")')
912

@@ -106,9 +109,14 @@ def parse(self):
106109
while self.ptr<self.length-1:
107110
key = self.__parse_key()
108111

109-
# Tuple/List parsing
110112
self.consume_whitespace()
111-
if self.s[self.ptr] in ('(', '['):
113+
# Multi-line HAML
114+
if self.s[self.ptr] == '\n':
115+
self.ptr+=1
116+
val=self.__parse_haml()
117+
self.consume_whitespace()
118+
# Tuple/List parsing
119+
elif self.s[self.ptr] in ('(', '['):
112120
tl_parser = AttributeTupleAndListParser(self.s[self.ptr:])
113121
val = tl_parser.parse()
114122
self.ptr += tl_parser.ptr
@@ -118,6 +126,22 @@ def parse(self):
118126

119127
self.dict[key]=val
120128
return self.dict
129+
130+
def __parse_haml(self):
131+
def whitespace_length():
132+
r = re_whitespace.match(self.s, pos=self.ptr)
133+
return len(r.group(0))
134+
135+
initial_indentation=whitespace_length()
136+
lines = []
137+
while whitespace_length() >= initial_indentation:
138+
line=re_line.match(self.s, pos=self.ptr).group(0)
139+
lines.append(line)
140+
self.ptr += len(line)+1
141+
142+
h=hamlpy.Compiler()
143+
html = h.process_lines(lines)
144+
return re.sub(re_leading_spaces, ' ', html).replace('\n', '').strip()
121145

122146
def __parse_key(self):
123147
'''Parse key variable and consume up to the colon'''

hamlpy/test/attribute_dict_parser_test.py

+20
Original file line numberDiff line numberDiff line change
@@ -85,3 +85,23 @@ def test_attribute_value_not_quoted_when_looks_like_key(self):
8585
eq_(dict.get('content'), 'width:device-width, initial-scale:1, minimum-scale:1, maximum-scale:1')
8686
eq_(dict.get('name'), 'viewport')
8787

88+
89+
def test_multiline_haml_in_attributes(self):
90+
s="""{
91+
'class':
92+
- if forloop.first
93+
link-first
94+
- else
95+
- if forloop.last
96+
link-last
97+
'href':
98+
- url 'some_view'
99+
}"""
100+
dict=AttributeDictParser(s).parse()
101+
eq_(dict.get('class'), '{% if forloop.first %} link-first {% else %} {% if forloop.last %} link-last {% endif %} {% endif %}')
102+
eq_(dict.get('href'), "{% url 'some_view' %}")
103+
104+
# \r\n and \n
105+
# Curly braces in multiline HAML
106+
# Blank lines in Multiline HAML
107+
# Incorrectly indented multiline HAML

0 commit comments

Comments
 (0)