jessemiller / hamlpy Goto Github PK
View Code? Open in Web Editor NEWA converter of HAML like templates into Django templates.
License: MIT License
A converter of HAML like templates into Django templates.
License: MIT License
current trunk's hamlpy_watcher.py
has fullpath
as an unbound name:
(dj) sa@wks:~/0/1/dj/pr$ la templates/
total 24
drwxr-xr-x 3 sa sa 4096 Sep 25 15:59 .
drwxr-xr-x 7 sa sa 4096 Sep 25 15:37 ..
drwxr-xr-x 2 sa sa 4096 Sep 3 14:34 admin
-rw-r--r-- 1 sa sa 151 Sep 18 19:01 base_blog.haml
-rw-r--r-- 1 sa sa 1148 Sep 25 14:56 base.haml
-rw-r--r-- 1 sa sa 156 Sep 18 19:04 blog_post.haml
(dj) sa@wks:~/0/1/dj/pr$ hamlpy-watcher templates/
Watching /home/sa/0/1/dj/pr/templates at refresh interval 3 seconds
Traceback (most recent call last):
File "/home/sa/0/1/dj/bin/hamlpy-watcher", line 9, in <module>
load_entry_point('hamlpy==0.3', 'console_scripts', 'hamlpy-watcher')()
File "/home/sa/.pip/source/hamlpy/hamlpy/hamlpy_watcher.py", line 38, in watch_folder
_watch_folder(folder, destination)
File "/home/sa/.pip/source/hamlpy/hamlpy/hamlpy_watcher.py", line 54, in _watch_folder
mtime = os.stat(fullpath).st_mtime
UnboundLocalError: local variable 'fullpath' referenced before assignment
(dj) sa@wks:~/0/1/dj/pr$
Accordingly to the documentation:
"A Django variable can also be used as content for any HTML element by placing an equals sign as the last character before the space and content"
it works great with tags but how about plain text?
- block heading
Title=django_variable
result:
<% block heading %>
Title=django_variable
<% endblock %>
I don't know if this is PyPI's issue or there was an error while uploading the package, but I can't run buildout with hamlpy version 0.81.2:
Getting distribution for 'hamlpy>=0.81'.
While:
Installing django.
Getting distribution for 'hamlpy>=0.81'.
Error: Couldn't find a distribution for 'hamlpy>=0.81'.
would like to set an image's source attribute like this:
%img {'src': '= item.thumbnail'}
but I ended up doing this:
:python
print "<img src='{{ item.thumbnail }}' />"
I'm not sure if I am doing it wrong or HamPy is doing it wrong. If if turns out this is a bug, I'm happy to step in and fix it, but it could very well be an error on my part.
https://github.com/jessemiller/HamlPy/blob/master/reference.md should show an example for inline variable usage as otherwise folks would need to literally write
Hello
= user.name
,how are you today?
instead of just Hello #{user.name}, how are you today?
Inline variables were added about two years ago with #17
The following example from reference.md defines "item" and "description" as being class names but in the output they are used as id:s
#collection
.item
.description What a cool item!
will compile to:
<div id='collection'>
<div id='item'>
<div id='description'>What a cool item!</div>
</div>
</div>
I encounter a fallowing bug:
parcing the line (taking properties of the variable 'user'):
%i.icon-user{'id': 'UserInfo','data-is-staff': '= user.is_stuff', 'data-id':'= user.pk'}
results in
in order to have it worked propetly i made a workaround:
- with user_is_stuff=user.is_stauff user_pk=user.pk
%i.icon-user{'id': 'UserInfo','data-is-staff': '= user_is_stuff', 'data-id':'= user_pk'}
that results in right output:
{% with user_is_stuff=user.is_stauff user_pk=user.pk %}
{% endwith %}
Attributes that have value 1 are ignored.
Input: %input{value:"1"}
Expected output: <input class='required' value='1' />
Actual output: <input class='required' value />
Test:
def test_attribute_value_containing_1(self):
haml = '%input{value:"1"}'
html = "<input class='required' value='1' />"
hamlParser = hamlpy.Compiler()
result = hamlParser.process(haml)
self.assertEqual(html, result.replace('\n', ''))
I'll take a look at this next week.
Is there a way to include Javascript on the page? I tried to use the :javascript syntax from Haml, but no luck.
The wiki example for multiple attributes in a dict doesn't seem to work with the current version of HamlPy:
%div{'id': ('article', '3'), 'class': ('newest', 'urgent')} Content
produces
<div id='article_3' class='('newest', 'urgent')'>Content
I've found a bug that destroys Javascript linebreaks.
Here's the bug in a simple form. The first :javascript becomes broken, the second does not.
:javascript
(
{
a
}
);
:javascript
{
a
}
)
Here's the output:
<script type='text/javascript'>
// <![CDATA[
(
{ a }
);
// ]]>
</script>
<script type='text/javascript'>
// <![CDATA[
{
a
}
)
// ]]>
</script>
Here's a template that has the bug too: http://pastebin.com/ZDfjF6ed
While editing emacs for some reason creates broken symlinks like .#base.haml -> [email protected]:1224901752
Hamlpy-watcher do not provide any way to ignore them and fails with traceback when it tries to convert them.
Django 1.4 supports, HamlPy should also do.
Now if you print:
HamlPy failed to save file with utf-8 characters.
Traceback (most recent call last):
File "/usr/local/bin/hamlpy", line 9, in <module>
load_entry_point('hamlpy==0.1b1', 'console_scripts', 'hamlpy')()
File "/usr/local/lib/python2.6/dist-packages/hamlpy-0.1b1-py2.6.egg/hamlpy/hamlpy.py", line 31, in convert_files outFile.write(output)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128)
Not sure if this is HamlPy's problem or if it's pip's problem. at any rate, it looks like pip tries to install the Mac OS version, and then fails because it can't find setup.py. I'm running Fedora 15. Here's the relevant error:
$ pip install hamlpy
Downloading/unpacking hamlpy
Downloading hamlpy-0.6.macosx-10.7-intel.tar.gz
Running setup.py egg_info for package hamlpy
Traceback (most recent call last):
File "<string>", line 14, in <module>
IOError: [Errno 2] No such file or directory: '[VE]/build/hamlpy/setup.py'
Complete output from command python setup.py egg_info:
Traceback (most recent call last):
File "<string>", line 14, in <module>
IOError: [Errno 2] No such file or directory: '[VE]/build/hamlpy/setup.py'
Hello,
In some case the Element node have no attribute element (in comments it seems), so the function crash when trying to call self.element in : hamlpy/nodes.py", line 282, in _post_render
To reproduce :
Write this in a file : test.haml
-# My comment
#my_div
my text
then execute hamlpy test.haml
When you do something like this
- if var
- for thing in things
%div= thing
- else
%div no things
The else is always happening for some reason.
ideally - all standard django tags, i.e. spaceless
I've converted my project to HamlPy and Djaml, and everything works fine except the i18n.
%b
- trans 'Some message text'
This trans
tag is ignored by make_messages command, as well as blocktrans
in haml syntax. After running manage.py make_messages
I found all the messages from templates commented out as they were not found.
I know I can fall back to usual syntax like
%b {% trans 'Some message text' %}
but it undoes a lot of gains of haml. Is there a way to make the translation parser recognize haml syntax?
as the 'big' HAML does:
/[if lt IE 9]
%script{'src': "fix-fckng-ie.com/fixit.js"}
I have a function like this where I need to use inline quoting because it's an attribute:
%meta{"name": "description", "content": "{% block description %}{{ _("Some text to translate") }}{% endblock %}"}
This outputs:
<meta content='{% block description %}{{ _(\'Learning for everyone, by everyone, about almost anything.\') }}{% endblock %}' name='description' />
The _() function is our translation function. It's argument needs to not be quoted! Is it possible to turn this off in some option.
As you probably know, pip allows installing from a git repo, see http://www.pip-installer.org/en/latest/requirement-format.html#git
It would be nice if you add tag "v0.2" for the last version.
Thanks
I believe this is a regression from the commit:
"fixing nesting of if and for with else. Addresses https://github.com/jessemiller/HamlPy/issues#issue/5"
f0ab3a6
Sometimes element's attributes can depends on some logic or django variables, for example:
{% for a in b %}
<a class="link {% if forloop.first %}link-first {% else %}{% if forloop.last %}link-last{% endif %}{% endif %}">this is link</a>
{% endfor %}
I want to do it in haml-way, but this is impossible in the current version of hamlpy
(I'll fix this myself when I get time, just leaving this as a reminder/discussion)
The following code causes a problem
#world{data-page:"hello"}
But not this:
#world{"data-page":"hello"}
Although I don't think HamlPy explicitly supports attributes without quotes, they generally work anyway (and I think it's good to support as it involves less unnecessary typing (equals less errors)). The dash just seems to throw it off
running the command:
hamlpy reference.md
crashes in elements.py at line 67:
#attribute_dict_string = re.sub(r'=(?P[a-zA-Z_][a-zA-Z0-9_.]+)', "'{{\g}}'", attribute_dict_string)
attributes_dict = eval(attribute_dict_string)
The following diff makes changes to reference.md so it can be correctly parsed.
--- a/reference.md
+++ b/reference.md
@@ -118,7 +118,7 @@ is compiled to:
These shortcuts can be combined with the attribute dictionary and they will be
- %div#Article.article.entry{'id':'1', class='visible'} Booyaka
+ %div#Article.article.entry{'id':'1', 'class': 'visible'} Booyaka
is equivalent to:
@@ -237,7 +237,7 @@ is compiled to:
A Django variable can also be used as content for any HTML element by placing a
%h2
- %a{'href'='stories/1'}= story.teaser
+ %a{'href': 'stories/1'}= story.teaser
is compiled to:
I need to inser localized value into input field
%input{'name':'text', 'type':'text', 'value':'localized_value'}
need to be like
%input{'name':'text', 'type':'text', 'value':'
- trans
Введите значение'}
How can i do that?
Hi,
I noticed that you can separate long dictionary values for a tag like %script. I tried that, and it worked.
But if I try to do this:
%div{'class': 'row'}
%img{'src': '/static/imgs/ibl_logo.gif',
'alt': 'IBL Logo'}
%br
It does not work and second line, i.e. 'alt' tag prints on a second line. I have tried different ways to see if it could work but I am lost at it and hence decided to file it as a bug. If it is not, my apologies.
Just a couple of examples.
Works:
#content.partial_update.page.oldSchool
- block content
%h1 En el bar has encontrado a tus conocidos juntos. Están alegres y te dicen que van a casarse entre un mes.
But:
- blocktrans with object.duration_as_time as dur
%span.jtimer.bigger {{ dur }}
remain
- endblocktrans
I have to close blocktrans
manually.
What can be done to make it work automatically?
This:
%head
:javascript
$(document).ready(function(){
$("#form{{form.initial.id}}").submit(form_submit);
// Javascript comment
});
:css
.someClass {
width: 100px;
}
:cdata
if (a < b && a < 0)
{
return 1;
}
should compile to this:
<head>
<script type='text/javascript'>
// <![CDATA[
$(document).ready(function(){
$("#form{{form.initial.id}}").submit(form_submit);
// Javascript comment
});
// ]]>
</script>
<style type='text/css'>
/*<![CDATA[*/
.someClass {
width: 100px;
}
/*]]>*/
</style>
<![CDATA[
if (a < b && a < 0)
{
return 1;
}
]]>
<head>
but instead, it compiles to this:
<head>
<script type='text/javascript'>
// <![CDATA[
$(document).ready(function(){ $("#form{{form.initial.id}}").submit(form_submit); // Javascript comment });
// ]]>
</script>
<style type='text/css'>
/*<![CDATA[*/
.someClass { width: 100px; }
/*]]>*/
</style>
<![CDATA[
if (a < b && a < 0)
{ return 1; }
]]>
</head>
Basically nothing about the highlight filter seems to work.
Running hamlpy_test.py you get:
Ran 28 tests in 0.004s
OK
When in fact test_pygments_filter should fail but the test doesn't seem to be run due to indentation problems in hamlpy_test.py, there's mixed tabs and spaces. After fixing that I get:
======================================================================
FAIL: test_pygments_filter (__main__.HamlPyTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "hamlpy_test.py", line 213, in test_pygments_filter
eq_(html, result)
File "/home/lashni/dev/karasu/lib/python2.7/site-packages/nose/tools.py", line 31, in eq_
assert a == b, msg or "%r != %r" % (a, b)
AssertionError: '<div class="highlight"><pre><span class="k">print</span> <span class="err">"</span><span class="n">Hello</span><span class="p">,</span> <span class="n">HamlPy</span> <span class="n">World</span><span class="o">!</span></pre></div>' != ':highlight\nprint "Hello, HamlPy World!\n'
----------------------------------------------------------------------
Ran 29 tests in 0.005s
FAILED (failures=1)
Looking at PygmentsFilterNode within nodes.py:
from pygments import highlight
from pygments.formatters import HtmlFormatter
from pygments.lexers import guess_lexer, guess_lexer_for_filename
class PygmentsFilterNode(FilterNode):
def render(self):
output = self.spaces
output += highlighter(self.haml, guess_lexer(self.haml), HtmlFormatter())
return output
guess_lexer_for_filename is an unused import, output+= highlighter should be highlight.
After making these changes it's still broken, I'm currently working on it. Will update later.
It doesn't appear as though hamlpy supports html-style attributes. I'll work on implementing something and submit a pull.
http://haml-lang.com/docs/yardoc/file.HAML_REFERENCE.html#htmlstyle_attributes_
First of all: thanks for your work! This is really great!
Do you plan to add a watcher script, such that changed files with the .hamlpy extension get automatically compiled? I was thinking of writing it myself, but I'm not sure if polling would be better than inotify (cross-platform vs. performance). Also, fssm would be an option (http://chriseppstein.github.com/blog/2009/09/07/building-a-jekyll-watcher-with-fssm/), but then again... that's ruby code in a python project...
pip install hamlpy
fails with
Could not find any downloads that satisfy the requirement hamlpy
Worked it around by installing directly from github, but would prefer having it installed in a normal way
I'm trying to work with HamlPy and blueprint-css. For the latter I need css class names like 'span-24'. When I write the following HamlPy markup:
.header.span-24.last
I get:
My curent workaround is:
.header.last{'class':'span-24'}
which yields the expected result
The other acceptable solution
%div{'class':('header', 'last', 'span-24')}
doesn't work because of Issue #9
This fails in the new version:
%meta{name:"viewport", content:"width:device-width, initial-scale:1, minimum-scale:1, maximum-scale:1"}
Result:
Traceback (most recent call last):
File "/Users/vbabiy/.virtualenvs/hamlpy/bin/hamlpy", line 8, in <module>
load_entry_point('hamlpy==0.80.3', 'console_scripts', 'hamlpy')()
File "/Users/vbabiy/.virtualenvs/hamlpy/lib/python2.7/site-packages/hamlpy/hamlpy.py", line 42, in convert_files
output = compiler.process_lines(haml_lines)
File "/Users/vbabiy/.virtualenvs/hamlpy/lib/python2.7/site-packages/hamlpy/hamlpy.py", line 29, in process_lines
return root.render()
File "/Users/vbabiy/.virtualenvs/hamlpy/lib/python2.7/site-packages/hamlpy/nodes.py", line 123, in render
return self.render_internal_nodes()
File "/Users/vbabiy/.virtualenvs/hamlpy/lib/python2.7/site-packages/hamlpy/nodes.py", line 126, in render_internal_nodes
return ''.join([node.render() for node in self.internal_nodes])
File "/Users/vbabiy/.virtualenvs/hamlpy/lib/python2.7/site-packages/hamlpy/nodes.py", line 185, in render
return self._render_tag()
File "/Users/vbabiy/.virtualenvs/hamlpy/lib/python2.7/site-packages/hamlpy/nodes.py", line 188, in _render_tag
self.element = Element(self.haml)
File "/Users/vbabiy/.virtualenvs/hamlpy/lib/python2.7/site-packages/hamlpy/elements.py", line 36, in __init__
self._parse_haml()
File "/Users/vbabiy/.virtualenvs/hamlpy/lib/python2.7/site-packages/hamlpy/elements.py", line 41, in _parse_haml
self.attributes_dict = self._parse_attribute_dictionary(split_tags.get('attributes'))
File "/Users/vbabiy/.virtualenvs/hamlpy/lib/python2.7/site-packages/hamlpy/elements.py", line 123, in _parse_attribute_dictionary
raise Exception('failed to decode: %s'%attribute_dict_string)
Exception: failed to decode: {"name":"viewport", "content":"width:device-width, "initial-scale":1, "minimum-scale":1, "maximum-scale":1"}
Rather than ending a block with just {% endblock %}
{% block content %}
...
{% endblock %}
I think it would help readability if it would carry the block name such as
{% block content %}
...
{% endblock content %}
See https://docs.djangoproject.com/en/dev/topics/templates/#template-inheritance for more info.
I'll revisit this, just leaving it as a reminder while I'm working on #78
This works:
%p
%li Item one
%li> Item two
%li Item three
This doesn't:
%li Item one
%li> Item two
%li Item three
Outer whitespace removal runs when a node tries to render its internal children (this is so we can have access to the rendered siblings to strip the whitespace). In the second example the parent is the RootNode, rather than a HamlNode, so render_internal_nodes is never called.
hamlpy-watcher.py watches all subdirectories in the source directory, but when it compiles the files, it puts them all into the same folder instead of mirroring the directory structure of the source folder.
With Django 1.5 we have to enclose the first argument to the url
template tag in single quotes thus HamlPy needs to recognize stuff like %a{'href':'{% url 'auth_login' %}'} login
without the need to escape the first argument's single quotes with backslashes. Right now one has to use ' as with this example %a{'href':'{% url \'auth_login\' %}'} login
in order to get <a href='{% url 'auth_login' %}'>login</a>
.
For more info see https://docs.djangoproject.com/en/dev/internals/deprecation/#id2
The url and ssi template tags will be modified so that the first argument to each tag is a template variable, not an implied string. Until then, the new-style behavior is provided in the future template tag library.
I may be blind here but I can't find anywhere in the docs or code about how to specify the HTML doctype. Will this be added soon?
Hey there,
first of all: Thank you for your effort in bringing HAML to the Python world. I’m coming from a Ruby background and your implementation makes me feel at home. :)
I’ve a quick question – in the original HAML there is the possibility to control whitespace output.
See the HAML-Documentation about Whitespace
I’m wondering if something similar exists in your implementation … the feature is especially important when it comes to inline-blocks because they are whitespace-aware and I need an output without any whitespace between them.
Any help on the matter would be greatly appreciated. :)
Best regards,
Harry
For example, I can't write:
#blah{'class': minor}
Which compiles to:
<div id="blah" class="{{ minor }}"></div>
However I could write:
#blah{'class': '{{ minor }}'}
But this is inconsistent.
action: "{% url 'django.contrib.auth.views.login' %}"
renders as:
`action='{% url "django.contrib.auth.views.login" %}'``
Which is obviously problematic. Had a poke around the code but I'm not familiar enough with it yet to track down the problem.
Is there a need to escape apostrpohes at all. Given that it's a developers language I don't see any security risk posed by it.
How can I write something that outputs this:
<input type='hidden' name='csrfmiddlewaretoken' value='bb2bc91aba0f29f3aacae0029a822dc9' />
where the value of the value attribute is {{ csrf_token }} in django's templates.
Example:
- mytag
Add stuff here
compiles to:
{% mytag %}
Add stuff here
{% endmytag %}
It'd be nice to support these and just assume/require that we adhere to typical django naming conventions (e.g. the closing tag starts with "end").
Right now there's no way to output the ever-so-standard
<script src="my-cool-script.js"></script>
Since you have an explicit way to self-close the tag (/), it would be better to always close the tag in the standard way in the absence of that explicit slash.
When parsed tabs are converted to 1 space rather than a full tab in HTML. Maybe there is a setting but have not been able to locate it so answer things question may help others that run into this issue.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.