1

I'm trying to use django as a stand alone template engine. This works fine based on this I tried to add a simple filter, but the template isn't able to use it

The basic example code is:

from django.template import Template, Context, Library
from django.conf import settings
settings.configure()

register = Library()

@register.filter
def nothing(value):
    return value

template = '''
{{var|nothing}}
'''

t = Template(template)
c = Context({'var':1})
print (t.render(c))

and the error is:

Traceback (most recent call last):
  File "C:/dev/git/ophir/dj.py", line 20, in <module>
    t = Template(template)
  File "C:\Python27\lib\site-packages\django\template\base.py", line 190, in __init__
    self.nodelist = engine.compile_string(template_string, origin)
  File "C:\Python27\lib\site-packages\django\template\engine.py", line 261, in compile_string
    return parser.parse()
  File "C:\Python27\lib\site-packages\django\template\base.py", line 317, in parse
    filter_expression = self.compile_filter(token.contents)
  File "C:\Python27\lib\site-packages\django\template\base.py", line 423, in compile_filter
    return FilterExpression(token, self)
  File "C:\Python27\lib\site-packages\django\template\base.py", line 633, in __init__
    filter_func = parser.find_filter(filter_name)
  File "C:\Python27\lib\site-packages\django\template\base.py", line 429, in find_filter
    raise TemplateSyntaxError("Invalid filter: '%s'" % filter_name)
django.template.base.TemplateSyntaxError: Invalid filter: 'nothing'

Process finished with exit code 1

Any ideas?

Community
  • 1
  • 1
Ophir Yoktan
  • 8,149
  • 7
  • 58
  • 106

1 Answers1

3

You need to follow the instructions in the Code Layout section of the docs, there isn't any way around it.

Therefore, you need to include {% load my_template_tags %} inside the template string, and include the app that includes the templatetags/my_template_tags.py module in your INSTALLED_APPS setting.

You may find it easier to use Jinja2, which can be used as a stand alone template engine.

Alasdair
  • 298,606
  • 55
  • 578
  • 516