def test_read_element(self): stream = Stream( '%angular:ng-repeat.my-class#my-id(class="test")></= Hello \n.next-element' ) element = read_element(stream, Compiler()) self.assertEqual(element.tag, 'angular:ng-repeat') self.assertEqual(element.id, 'my-id') self.assertEqual(element.classes, ['test', 'my-class']) self.assertEqual(dict(element.attributes), {'class': "test"}) self.assertEqual(element.nuke_outer_whitespace, True) self.assertEqual(element.nuke_inner_whitespace, True) self.assertEqual(element.self_close, True) self.assertEqual(element.django_variable, True) self.assertEqual(element.inline_content, "Hello") self.assertEqual(stream.text[stream.ptr:], '.next-element') stream = Stream('%input{required} ') element = read_element(stream, Compiler()) self.assertEqual(element.tag, 'input') self.assertEqual(element.id, None) self.assertEqual(element.classes, []) self.assertEqual(dict(element.attributes), {'required': True}) self.assertEqual(element.nuke_outer_whitespace, False) self.assertEqual(element.nuke_inner_whitespace, False) self.assertEqual(element.self_close, True) # input is implicitly self-closing self.assertEqual(element.django_variable, False) self.assertEqual(element.inline_content, '') self.assertEqual(stream.text[stream.ptr:], '')
def _test(self, haml, expected_html, compiler_options=None): compiler = Compiler(compiler_options) result = compiler.process(haml) result = result.rstrip('\n') # ignore trailing new lines assert result == expected_html
def templatize(src, origin=None): # if the template has no origin then don't attempt to convert it because we don't know if it's Haml if origin: extension = os.path.splitext(origin.name)[1][1:].lower() if extension in HAML_EXTENSIONS: compiler = Compiler() src = compiler.process(src) return func(src, origin)
def _test(self, haml, expected_html, options=None): if not options: options = {'escape_attrs': True} compiler = Compiler(options) result = compiler.process(haml) result = result.rstrip('\n') # ignore trailing new lines assert result == expected_html
def templatize(src, origin=None): # if the template has no origin then don't attempt to convert it because we don't know if it's Haml if origin: extension = os.path.splitext(origin)[1][1:].lower() if extension in HAML_EXTENSIONS: compiler = Compiler() src = compiler.process(src) return func(src, origin=origin)
def preprocess(self, source, name, filename=None): extension = os.path.splitext(name)[1][1:] if extension in HAML_EXTENSIONS: compiler = Compiler() try: return compiler.process(source) except ParseException as e: raise jinja2.TemplateSyntaxError(six.text_type(e), 1, name=name, filename=filename) else: return source
def test_read_filter_node(self): stream = Stream(':python\n print("hello")\n') node = read_filter_node(stream, '', Compiler()) assert node.filter_name == 'python' assert node.content == ' print("hello")' assert stream.text[stream.ptr:] == '' stream = Stream(':javascript\n var i = 0;\n var j = 1;\n%span') node = read_filter_node(stream, '', Compiler()) assert node.filter_name == 'javascript' assert node.content == ' var i = 0;\n var j = 1;' assert stream.text[stream.ptr:] == '%span'
def get_contents(self, origin): # Django>=1.9 contents = super(Loader, self).get_contents(origin) name, _extension = os.path.splitext(origin.template_name) # os.path.splitext always returns a period at the start of extension extension = _extension.lstrip(".") if extension in HAML_EXTENSIONS: compiler = Compiler(options=options) return compiler.process(contents) return contents
def _test_error(self, haml, expected_message, expected_cause=None, compiler_options=None): compiler = Compiler(compiler_options) try: compiler.process(haml) self.fail("Expected exception to be raised") except Exception as e: self.assertIsInstance(e, ParseException) assert str(e) == expected_message if expected_cause: assert type(e.__cause__) == expected_cause
def get_contents(self, origin): # Django>=1.9 contents = super(Loader, self).get_contents(origin) name, _extension = os.path.splitext(origin.template_name) # os.path.splitext always returns a period at the start of extension extension = _extension.lstrip('.') if extension in HAML_EXTENSIONS: compiler = Compiler(options=options) return compiler.process(contents) return contents
def preprocess(self, source, name, filename=None): extension = os.path.splitext(name)[1][1:] if extension in HAML_EXTENSIONS: compiler = Compiler() try: return compiler.process(source) except ParseException as e: raise jinja2.TemplateSyntaxError(str(e), 1, name=name, filename=filename) else: return source
def test_django_tags(self): # if/else self._test('- if something\n %p hello\n- else\n %p goodbye', '{% if something %}\n <p>hello</p>\n{% else %}\n <p>goodbye</p>\n{% endif %}') # with self._test('- with thing1 as another\n stuff', '{% with thing1 as another %}\n stuff\n{% endwith %}') self._test('- with context\n hello\n- with other_context\n goodbye', '{% with context %}\n hello\n{% endwith %}\n{% with other_context %}\n goodbye\n{% endwith %}') # trans self._test('- trans "Hello"\n', '{% trans "Hello" %}') # blocktrans self._test('- blocktrans with amount=num_cookies\n' ' There are #{ amount } cookies', '{% blocktrans with amount=num_cookies %}\n' ' There are {{ amount }} cookies\n' '{% endblocktrans %}') self._test('- blocktrans with amount=num_cookies\n' ' There is one cookie\n' '- plural\n' ' There are #{ amount } cookies', '{% blocktrans with amount=num_cookies %}\n' ' There is one cookie\n' '{% plural %}\n' ' There are {{ amount }} cookies\n' '{% endblocktrans %}') # exception using a closing tag of a self-closing tag parser = Compiler() self.assertRaises(ParseException, parser.process, '- endfor')
def get_contents(self, origin): # Django>=1.9 contents = super(Loader, self).get_contents(origin) print 'start load template: ' + origin.template_name name, _extension = os.path.splitext( origin.template_name ) # os.path.splitext always returns a period at the start of extension extension = _extension.lstrip('.') if extension in HAML_EXTENSIONS: compiler = Compiler(options=options) t = clock() if HAML_UNIT.ENABLE: dtaml = HamlComponent(origin, contents) print 'HamlComponent create: ' + str(clock() - t) res_keeper = dtaml.package_ress() print 'package_ress: ' + str(clock() - t) contents = dtaml.embed_components() print 'embed_components: ' + str(clock() - t) print '++++++++++++++++++++++++++++++++++++++++++++++++ hamlpy components completed' ## now contents is full. Prepare it: contents = clean_sugar(contents) ## save contents before compiler haml_file = str(origin).rsplit('.', 1)[0] + '__log' + '.haml' with open(haml_file, 'w') as pen: pen.write(contents) ## contents = contents.decode('utf-8') if type(contents) is str else contents html_content = compiler.process(contents) ## save result after compiling html_file = str(origin).rsplit('.', 1)[0] + '.html' with open(html_file, 'w') as html: html.write(html_content) return html_content return contents
def get_contents(self, origin): """ Used by Django 1.9+ """ name, _extension = os.path.splitext(origin.name) template_name, _extension = os.path.splitext(origin.template_name) for extension in HAML_EXTENSIONS: try_name = self._generate_template_name(name, extension) try_template_name = self._generate_template_name(template_name, extension) try_origin = Origin(try_name, try_template_name, origin.loader) try: haml_source = super(Loader, self).get_contents(try_origin) except TemplateDoesNotExist: pass else: haml_parser = Compiler() return haml_parser.process(haml_source) raise TemplateDoesNotExist(origin.template_name)
def load_template_source(self, template_name, *args, **kwargs): # Django<1.9 name, _extension = os.path.splitext(template_name) # os.path.splitext always returns a period at the start of extension extension = _extension.lstrip('.') if extension in HAML_EXTENSIONS: try: haml_source, template_path = super(Loader, self).load_template_source( self._generate_template_name(name, extension), *args, **kwargs ) except TemplateDoesNotExist: # pragma: no cover pass else: compiler = Compiler(options=options) html = compiler.process(haml_source) return html, template_path raise TemplateDoesNotExist(template_name)
def get_contents(self, origin): """ Used by Django 1.9+ """ name, _extension = os.path.splitext(origin.name) template_name, _extension = os.path.splitext(origin.template_name) for extension in HAML_EXTENSIONS: try_name = self._generate_template_name(name, extension) try_template_name = self._generate_template_name(template_name, extension) try_origin = Origin(try_name, try_template_name, origin.loader) try: haml_source = super().get_contents(try_origin) except TemplateDoesNotExist: pass else: haml_parser = Compiler() return haml_parser.process(haml_source) raise TemplateDoesNotExist(origin.template_name)
def load_template_source(self, template_name, *args, **kwargs): # Django<1.9 name, _extension = os.path.splitext(template_name) # os.path.splitext always returns a period at the start of extension extension = _extension.lstrip(".") if extension in HAML_EXTENSIONS: try: haml_source, template_path = super(Loader, self).load_template_source( self._generate_template_name(name, extension), *args, **kwargs ) except TemplateDoesNotExist: # pragma: no cover pass else: compiler = Compiler(options=options) html = compiler.process(haml_source) return html, template_path raise TemplateDoesNotExist(template_name)
def compile_file(fullpath, outfile_name, compiler_args): """ Calls HamlPy compiler. Returns True if the file was compiled and written successfully. """ if Options.VERBOSE: print('%s %s -> %s' % (strftime("%H:%M:%S"), fullpath, outfile_name)) try: if Options.DEBUG: # pragma: no cover print("Compiling %s -> %s" % (fullpath, outfile_name)) haml = codecs.open(fullpath, 'r', encoding='utf-8').read() compiler = Compiler(compiler_args) output = compiler.process(haml) outfile = codecs.open(outfile_name, 'w', encoding='utf-8') outfile.write(output) return True except Exception as e: # import traceback print("Failed to compile %s -> %s\nReason:\n%s" % (fullpath, outfile_name, e)) # print traceback.print_exc() return False
class TemplateCheck(object): compiler = Compiler(options={'format': 'xhtml', 'escape_attrs': True}) def __init__(self, name, haml, html): self.name = name self.haml = haml self.expected_html = html.replace('\r', '') # ignore line ending differences self.actual_html = None @classmethod def load_all(cls): directory = os.path.dirname(__file__) + TEMPLATE_DIRECTORY tests = [] # load all test files for f in listdir(directory): haml_path = path.join(directory, f) if haml_path.endswith(TEMPLATE_EXTENSION): html_path = path.splitext(haml_path)[0] + '.html' haml = codecs.open(haml_path, encoding='utf-8').read() html = open(html_path, 'r').read() tests.append(TemplateCheck(haml_path, haml, html)) return tests def run(self): parsed = self.compiler.process(self.haml) # ignore line ending differences and blank lines self.actual_html = parsed.replace('\r', '') self.actual_html = regex.sub('\n[ \t]+(?=\n)', '\n', self.actual_html) def passed(self): return self.actual_html == self.expected_html
def run(self): compiler = Compiler() parsed = compiler.process(self.haml) # ignore line ending differences self.actual_html = parsed.replace('\r', '')
def _read_node(haml): return read_node(Stream(haml), None, Compiler())
def _read_element(text): return read_element(Stream(text), Compiler())
#! /usr/bin/env python3 from __future__ import print_function import sys from hamlpy.compiler import Compiler with open(sys.argv[1]) as f: haml = f.read() compiler = Compiler() html = compiler.process(haml) print(html)
def test_read_ruby_style_attribute_dict(self): # empty dict stream = Stream("{}><") assert dict(read_attribute_dict(stream, Compiler())) == {} assert stream.text[stream.ptr:] == '><' # string values assert dict(self._parse("{'class': 'test'} =Test")) == { 'class': 'test' } assert dict(self._parse("{'class': 'test', 'id': 'something'}")) == { 'class': 'test', 'id': 'something' } # integer values assert dict(self._parse("{'data-number': 0}")) == {'data-number': '0'} assert dict(self._parse("{'data-number': 12345}")) == { 'data-number': '12345' } # float values assert dict(self._parse("{'data-number': 123.456}")) == { 'data-number': '123.456' } assert dict(self._parse("{'data-number': 0.001}")) == { 'data-number': '0.001' } # None value assert dict(self._parse("{'controls': None}")) == {'controls': None} # boolean attributes assert dict( self._parse( "{disabled, class:'test', data-number : 123,\n foo:\"bar\"}") ) == { 'disabled': True, 'class': 'test', 'data-number': '123', 'foo': 'bar' } assert dict( self._parse( "{class:'test', data-number : 123,\n foo:\"bar\", \t disabled}" )) == { 'disabled': True, 'class': 'test', 'data-number': '123', 'foo': 'bar' } # attribute name has colon assert dict(self._parse("{'xml:lang': 'en'}")) == {'xml:lang': 'en'} # attribute value has colon or commas assert dict(self._parse("{'lang': 'en:g'}")) == {'lang': 'en:g'} assert dict( self._parse( '{name:"viewport", content:"width:device-width, initial-scale:1, minimum-scale:1, maximum-scale:1"}' ) ) == { 'name': 'viewport', 'content': 'width:device-width, initial-scale:1, minimum-scale:1, maximum-scale:1' } # double quotes assert dict(self._parse('{"class": "test", "id": "something"}')) == { 'class': 'test', 'id': 'something' } # no quotes for key assert dict(self._parse("{class: 'test', id: 'something'}")) == { 'class': 'test', 'id': 'something' } # whitespace is ignored assert dict( self._parse( "{ class \t : 'test', data-number: 123 }") ) == { 'class': 'test', 'data-number': '123' } # trailing commas are fine assert dict(self._parse("{class: 'test', data-number: 123,}")) == { 'class': 'test', 'data-number': '123' } # attributes split onto multiple lines assert dict( self._parse("{class: 'test',\n data-number: 123}")) == { 'class': 'test', 'data-number': '123' } # old style Ruby assert dict(self._parse("{:class => 'test', :data-number=>123}")) == { 'class': 'test', 'data-number': '123' } # list attribute values assert dict( self._parse( "{'class': [ 'a', 'b', 'c' ], data-list:[1, 2, 3]}")) == { 'class': ['a', 'b', 'c'], 'data-list': ['1', '2', '3'] } # tuple attribute values assert dict( self._parse( "{:class=>( 'a', 'b', 'c' ), :data-list => (1, 2, 3)}")) == { 'class': ['a', 'b', 'c'], 'data-list': ['1', '2', '3'] } # attribute order is maintained assert self._parse( "{'class': 'test', 'id': 'something', foo: 'bar'}") == OrderedDict( [('class', 'test'), ('id', 'something'), ('foo', 'bar')]) # attribute values can be multi-line Haml assert dict( self._parse("""{ 'class': - if forloop.first link-first \x20 - else - if forloop.last link-last 'href': - url 'some_view' }""") ) == { 'class': '{% if forloop.first %} link-first {% else %} {% if forloop.last %} link-last {% endif %} {% endif %}', # noqa 'href': "{% url 'some_view' %}" } # non-ascii attribute values assert dict(self._parse("{class: 'test\u1234'}")) == { 'class': 'test\u1234' }
def _parse(text): return read_attribute_dict(Stream(text), Compiler())