Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

web2py support / inline coffeescript tags #19

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions hamlpy/elements.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ class Element(object):
ID = '#'
CLASS = '.'

HAML_REGEX = re.compile(r"(?P<tag>%\w+)?(?P<id>#\w*)?(?P<class>\.[\w\.-]*)*(?P<attributes>\{.*\})?(?P<selfclose>/)?(?P<django>=)?(?P<inline>[^\w\.#\{].*)?")
HAML_REGEX = re.compile(r"(?P<tag>%\w+)?(?P<id>#\w*)?(?P<class>\.[\w\.-]*)*(?P<attributes>\{.*\})?(?P<selfclose>/)?(?P<template>=)?(?P<inline>[^\w\.#\{].*)?")

def __init__(self, haml):
self.haml = haml
Expand All @@ -19,7 +19,7 @@ def __init__(self, haml):
self.classes = None
self.attributes = ''
self.self_close = False
self.django_variable = False
self.template_variable = False
self.inline_content = ''
self._parse_haml()

Expand All @@ -31,7 +31,7 @@ def _parse_haml(self):
self.id = self._parse_id(split_tags.get('id'))
self.classes = ('%s %s' % (split_tags.get('class').lstrip(self.CLASS).replace('.', ' '), self._parse_class_from_attributes_dict())).strip()
self.self_close = split_tags.get('selfclose') or self.tag in self.self_closing_tags
self.django_variable = split_tags.get('django') != ''
self.template_variable = split_tags.get('template') != ''
self.inline_content = split_tags.get('inline').strip()

def _parse_class_from_attributes_dict(self):
Expand Down
19 changes: 14 additions & 5 deletions hamlpy/hamlpy.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,34 +2,43 @@
from nodes import RootNode, create_node

class Compiler:


def __init__(self,template_type='django'):
self.template_type = template_type

def process(self, raw_text):
split_text = raw_text.strip().split('\n')
return self.process_lines(split_text)

def process_lines(self, haml_lines):
root = RootNode()
for line in haml_lines:
haml_node = create_node(line)
haml_node = create_node(line, self.template_type)
root.add_node(haml_node)
return root.render()

def convert_files():
import sys
import codecs

template_type = 'django' #defaults to django; also supports web2py

if len(sys.argv) < 2:
print "Specify the input file as the first argument."
else:
infile = sys.argv[1]
haml_lines = codecs.open(infile, 'r', encoding='utf-8').read().splitlines()

compiler = Compiler()

if len(sys.argv) == 4: template_type = sys.argv[3]

compiler = Compiler(template_type)
output = compiler.process_lines(haml_lines)

if len(sys.argv) == 3:
if len(sys.argv) >= 3:
outfile = codecs.open(sys.argv[2], 'w', encoding='utf-8')
outfile.write(output)


else:
print output

Expand Down
10 changes: 7 additions & 3 deletions hamlpy/hamlpy_watcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,8 @@ def watched_extension(extension):

def watch_folder():
"""Main entry point. Expects exactly one argument (the watch folder)."""
if len(sys.argv) == 2:
"""Added additional argument for template_type after adding web2py template compatibility -Dane"""
if len(sys.argv) >= 2:
folder = os.path.realpath(sys.argv[1])
print "Watching %s at refresh interval %s seconds" % (folder,CHECK_INTERVAL)
while True:
Expand All @@ -39,7 +40,7 @@ def watch_folder():
sys.exit(0)
pass
else:
print "Usage: haml-watcher.py <watch_folder>"
print "Usage: haml-watcher.py <watch_folder> <template_type [optional, supports django(default), web2py]>"

def _watch_folder(folder):
"""Compares "modified" timestamps against the "compiled" dict, calls compiler
Expand All @@ -66,7 +67,10 @@ def compile_file(fullpath, outfile_name):
if DEBUG:
print "Compiling %s -> %s" % (fullpath, outfile_name)
haml_lines = codecs.open(fullpath, 'r', encoding='utf-8').read().splitlines()
compiler = Compiler()

template_type = sys.argv[2] if len(sys.argv) == 3 else 'django'

compiler = Compiler(template_type)
output = compiler.process_lines(haml_lines)
outfile = codecs.open(outfile_name, 'w', encoding='utf-8')
outfile.write(output)
Expand Down
90 changes: 66 additions & 24 deletions hamlpy/nodes.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,20 +12,21 @@
VARIABLE = '='
TAG = '-'

COFFEESCRIPT_FILTER = ':coffescript'
JAVASCRIPT_FILTER = ':javascript'
CSS_FILTER = ':css'
PLAIN_FILTER = ':plain'

ELEMENT_CHARACTERS = (ELEMENT, ID, CLASS)

def create_node(haml_line):
def create_node(haml_line, template_type='django'):
stripped_line = haml_line.strip()

if not stripped_line:
return None

if stripped_line[0] in ELEMENT_CHARACTERS:
return ElementNode(haml_line)
return ElementNode(haml_line, template_type)

if stripped_line[0] == HTML_COMMENT:
return CommentNode(haml_line)
Expand All @@ -34,14 +35,17 @@ def create_node(haml_line):
return HamlCommentNode(haml_line)

if stripped_line[0] == VARIABLE:
return VariableNode(haml_line)
return VariableNode(haml_line, template_type)

if stripped_line[0] == TAG:
return TagNode(haml_line)
return TagNode(haml_line, template_type)

if stripped_line == JAVASCRIPT_FILTER:
return JavascriptFilterNode(haml_line)

if stripped_line == COFFEESCRIPT_FILTER:
return CoffeeScriptFilterNode(haml_line)

if stripped_line == CSS_FILTER:
return CssFilterNode(haml_line)

Expand Down Expand Up @@ -100,16 +104,20 @@ def render(self):

class ElementNode(HamlNode):

def __init__(self, haml):
web2py_omit_equals = ['extend', 'include', 'super']
web2py_assignment = '\w+\s*=\s*.+'

def __init__(self, haml, template_type='django'):
HamlNode.__init__(self, haml)
self.django_variable = False
self.template_variable = False
self.template_type = template_type

def render(self):
return self._render_tag()

def _render_tag(self):
element = Element(self.haml)
self.django_variable = element.django_variable
self.template_variable = element.template_variable
return self._generate_html(element)

def _generate_html(self, element):
Expand Down Expand Up @@ -139,9 +147,23 @@ def _render_tag_content(self, current_tag_content):
current_tag_content = '\n' + self.render_internal_nodes() + self.spaces
if current_tag_content == None:
current_tag_content = ''
if self.django_variable:
current_tag_content = "{{ " + current_tag_content.strip() + " }}"
current_tag_content = re.sub(r'#\{([a-zA-Z0-9\.\_]+)\}', r'{{ \1 }}', current_tag_content)
if self.template_variable:
if self.template_type == 'django':
current_tag_content = "{{ " + current_tag_content.strip() + " }}"
elif self.template_type == 'web2py':
w2p_content = current_tag_content.strip()
w2p_prepend = '' if (re.search(self.web2py_assignment, w2p_content) or re.split('\W+',w2p_content)[0] in self.web2py_omit_equals) else '='
current_tag_content = "{{ " + w2p_prepend + w2p_content + " }}"

if self.template_type == 'django':
sub_re = r'#\{([a-zA-Z0-9\.\_]+)\}'
var_sub = r'{{ \1 }}'
elif self.template_type == 'web2py':
sub_re = r'#\{([a-zA-Z0-9\.\_]+(\(\))?)\}'
var_sub = r'{{ =\1 }}'

current_tag_content = re.sub(sub_re, var_sub, current_tag_content)

return current_tag_content


Expand Down Expand Up @@ -170,41 +192,55 @@ def render(self):


class VariableNode(ElementNode):
def __init__(self, haml):
ElementNode.__init__(self, haml)
self.django_variable = True
def __init__(self, haml, template_type='django'):
ElementNode.__init__(self, haml, template_type)
self.template_variable = True

def render(self):
tag_content = self.haml.lstrip(VARIABLE)
return "%s%s" % (self.spaces, self._render_tag_content(tag_content))


class TagNode(HamlNode):
self_closing = {'for':'endfor',
django_self_closing = {'for':'endfor',
'if':'endif',
'block':'endblock',
'filter':'endfilter',
'autoescape':'endautoescape',
}
may_contain = {'if':'else', 'for':'empty'}
web2py_self_closing = {'block':'end'}
web2py_ignore = ['elif:', 'else:', 'finally:', 'except.+:']
django_may_contain = {'if':'else', 'for':'empty'}

def __init__(self, haml):
def __init__(self, haml, template_type='django'):
HamlNode.__init__(self, haml)
self.tag_statement = self.haml.lstrip(TAG).strip()
self.tag_name = self.tag_statement.split(' ')[0]
self.tag_name = re.split('\W+', self.tag_statement)[0]
self.template_type= template_type

if (self.tag_name in self.self_closing.values()):
raise TypeError("Do not close your Django tags manually. It will be done for you.")
if (self.tag_name in self.django_self_closing.values() + self.web2py_self_closing.values()):
raise TypeError("Do not close your template tags manually. It will be done for you.")

def render(self):
internal = self.render_internal_nodes()
output = "%s{%% %s %%}\n%s" % (self.spaces, self.tag_statement, internal)
if (self.tag_name in self.self_closing.keys()):
output += '%s{%% %s %%}' % (self.spaces, self.self_closing[self.tag_name])
if self.template_type == 'django':
output = "%s{%% %s %%}\n%s" % (self.spaces, self.tag_statement, internal)
if (self.tag_name in self.django_self_closing.keys()):
output += '%s{%% %s %%}' % (self.spaces, self.django_self_closing[self.tag_name])
elif self.template_type == 'web2py':
output = "%s{{ %s }}\n%s" % (self.spaces, self.tag_statement, internal)
close_str = ''

if self.tag_name in self.web2py_self_closing:
close_str = self.web2py_self_closing[self.tag_name]
elif self.tag_statement[-1:] == ':' and not len([s for s in self.web2py_ignore if re.search(s, self.tag_statement)]):
close_str = 'pass'

if close_str: output += "%s{{ %s }}" % (self.spaces, close_str)
return output

def should_contain(self, node):
return isinstance(node,TagNode) and self.may_contain.get(self.tag_name,'') == node.tag_name
return isinstance(node,TagNode) and self.django_may_contain.get(self.tag_name,'') == node.tag_name


class FilterNode(HamlNode):
Expand All @@ -226,7 +262,13 @@ def render(self):
output += "".join([node.raw_haml for node in self.internal_nodes])
output += '// ]]>\n</script>'
return output


class CoffeeScriptFilterNode(FilterNode):
def render(self):
output = '<script type=\'text/coffeescript\'>\n// <![CDATA[\n'
output += "".join([node.raw_haml for node in self.internal_nodes])
output += '// ]]>\n</script>'
return output

class CssFilterNode(FilterNode):
def render(self):
Expand Down
Loading