Search code examples
pythonhtmltemplatesjinja2

HTML templating using Jinja2 - Lost


I am trying to create a html template in python using Jinja2. I have a templates folder with my 'template.html' but I don't know how to deal with environments or package loaders.

I installed Jinja2 using easy_python and ran the following script.

from jinja2 import Environment, PackageLoader
env = Environment(loader=PackageLoader('yourapplication', 'templates'))
template = env.get_template('mytemplate.html')
print template.render()

I get the following error because I don't know how to define a package/module. Please help me I just want to create a simple template.

  File "log_manipulationLL.py", line 291, in <module>
env = Environment(loader=PackageLoader('yourapplication', 'templates'))
 File "/usr/local/lib/python2.7/dist-packages/Jinja2-2.6-py2.7.egg/jinja2/loaders.py",    line 216, in __init__
provider = get_provider(package_name)
File "/usr/lib/python2.7/dist-packages/pkg_resources.py", line 213, in get_provider
__import__(moduleOrReq)
ImportError: No module named yourapplication

Solution

  • PackageLoader expects an actual Python module using the regular dot syntax. For example if your structure looks like this:

    myapp/
      __init__.py
      …
      templates/
        mytemplate.html
    

    You should use myapp as the module name.