0

I'm trying to write a custom jinja2 extension with Pyramid.

The extension code is:

from jinja2 import nodes
from jinja2.ext import Extension


class SnippetExtension(Extension):

    tags = set(['snippet'])

    def __init__(self, environment):
        print "Init"
        super(SnippetExtension, self).__init__(environment)

    def parse(self, parser):

        print "Parse"

        stream = parser.stream
        tag = stream.next()

        print "Writing"
        return nodes.Output('<div>Test</div>').set_lineno(tag.lineno)

I load the extension in __init__.py like this:

def main(global_config, **settings):
    """ This function returns a Pyramid WSGI application.
    """
    engine = engine_from_config(settings, 'sqlalchemy.')
    DBSession.configure(bind=engine)
    Base.metadata.bind = engine
    config = Configurator(settings=settings)
    config.include('pyramid_jinja2')
    config.include('pyramid_fanstatic')
    config.add_jinja2_renderer('.html')
    config.add_static_view('static', 'static', cache_max_age=3600)
    config.add_route('home', '/')
    add_jinja2_extension(config,SnippetExtension) #<--- load the extension
    config.scan()

    return config.make_wsgi_app()

However I get the error:

TemplateSyntaxError: Encountered unknown tag 'snippet'

When parting the template:

{% snippet %}

What else do I need to do or what am I doing wrong?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
QLands
  • 2,424
  • 5
  • 30
  • 50

1 Answers1

3

add_jinja2_extension is used for adding file extensions, not Jinja template extensions.

Template extensions should be listed in the jinja2.extensions entry instead.

You can pass those in with the settings mapping for example:

settings['jinja2.extensions'] = [SnippetExtension]
config = Configurator(settings=settings)
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343