问题描述
我正在尝试编写一个简单的jinja2
扩展名,该扩展名将在页面中呈现具有某些属性和内容属性的<meta>
标签.看起来像这样:
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')
还有
<!-- use it in the template -->
<head>
{% meta "key", "value" %}
</head>
尽管该标记在控制台中可以正常显示,但是当我在flask应用程序中使用该标记时,该标记会转义html并将转义的标记输出到页面.所以,而不是
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" />
我知道
<meta property="key" content="value" />
我做错了什么?谢谢.
推荐答案
原来,我应该一直使用nodes.CallBlock
而不是nodes.Output
.应用该更改后,parse
和_render
函数现在看起来像:
Turns out I should have been using nodes.CallBlock
instead of nodes.Output
. Applying that change, the parse
and _render
functions now look like:
...
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.CallBlock(self.call_method('_render', args),
[], [], []).set_lineno(tag.lineno)
def _render(self, value, name, *args, **kwargs):
return '<meta property="{}" content="{}" />'.format(value, name)
希望这对某人有帮助,因为Jinja2扩展参考(尤其是非阻塞标签)不是很容易获得:)
Hope this helps someone, as Jinja2 extension reference (especially for non-block tags) isn't easy to come by :)
这篇关于Jinja2扩展输出转义了html而不是html标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!