I'm trying to write a simple jinja2
extension that'll render a <meta>
tag in the page with some property and content attr. It looks something like this:
from jinja2 import nodes
from jinja2.ext import Extension
class MetaExtension(Extension):
"""
returns a meta tag of key, value
>> env = jinja2.Environment(extensions=[MetaExtension])
>> env.from_string('{% meta "key", "value" %}').render()
u'<meta property="keyword" content="value" />'
"""
# we'll use it in the template with
tags = set(['meta'])
def __init__(self, environment):
super(MetaExtension, self).__init__(environment)
def parse(self, parser):
tag = parser.stream.next()
args = [parser.parse_expression()]
if parser.stream.skip_if('comma'):
args.append(parser.parse_expression())
return nodes.Output([self.call_method('_render', args)]).set_lineno(tag.lineno)
def _render(self, *args):
return '<meta property="{}" content="{}" />'.format(args[0], args[1])
meta = MetaExtension
Using it in a flask app:
# register the extension in the app file
from flask import Flask
app = Flask(__name__)
app.jinja_env.add_extension('flask_meta.MetaExtension')
And
<!-- use it in the template -->
<head>
{% meta "key", "value" %}
</head>
Though the tag renders fine in the console, when I use it in a flask application it escapes the html and outputs the escaped tag to the page. So, instead of
<meta property="keyword" content="value" />
I get
<meta property="key" content="value" />
What am I doing wrong?