Pitmairen / hamlish-jinja

A haml-ish syntax for jinja2 templates
BSD 3-Clause "New" or "Revised" License
131 stars 11 forks source link

Environment.from_string query #10

Closed ghost closed 12 years ago

ghost commented 12 years ago

I can successfully render haml markup from file with Template and from string with Hamlish.convert_source but Environment.from_string just returns the raw haml instead of the expected html.

Not overly important but I'm curious.

ghost commented 12 years ago

Some test code:

from jinja2 import Environment, PackageLoader, Template
from hamlish_jinja import Hamlish, HamlishExtension, Output

env = Environment(loader=PackageLoader('karasu', 'pages'),
                  extensions=[HamlishExtension])
env.hamlish_mode='debug'

source = ('''
%p
    test''')

# Template
template = env.get_template('test.haml')
print template.render()
"""
<p>
   test</p>
"""

# convert_source
hamlish = Hamlish(Output(indent_string=' ', newline_string='\n'))
print hamlish.convert_source(source)
"""
<p>
 test
</p>
"""

# from_string
print env.from_string(source).render()
"""
%p
    test
"""
Pitmairen commented 12 years ago

This happens because before the source is converted there is a check to see if the file extension of the template is in "hamlish_file_extensions" which by default contains .haml, if the filename don't end with .haml the source is return unchanged. This is so to make it possible to mix haml and html template if you don't want all your templates to use haml syntax.

When using env.from_string there is no filename so the source is returned unchanged.

I guess i could add a configuration variable to force the use of haml on all templates.

You can also use the "HamlishTagExtension" and wrap you string with {%haml%}{%endhaml%}. This will work with env.from_string.

ghost commented 12 years ago

Makes sense to me now so I'm happy. :)

Yeah I might just wrap the string. My use case is pretty fringe so I wouldn't bother making any changes unless you think others are likely to come across the same thing.

Thanks

Pitmairen commented 12 years ago

The from_string method is pretty simple so you could do something like this:

class Environment(Environment):
    def from_string(self, source, globals=None, template_class=None):
          """Load a template from a string.  This parses the source given and
          returns a :class:`Template` object.
          """
          globals = self.make_globals(globals)
          cls = template_class or self.template_class
          return cls.from_code(self, self.compile(source, '<string>.haml'), globals, None)

This should force it to render haml.

ghost commented 12 years ago

Thanks for the help, I got my proof of concept working.

https://gist.github.com/2158678