Jinja2扩展输出转义了html而不是html标签 [英] Jinja2 extension outputs escaped html instead of html tag

查看:98
本文介绍了Jinja2扩展输出转义了html而不是html标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个简单的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" />

我知道

&lt;meta property=&#34;key&#34; content=&#34;value&#34; /&gt;

我做错了什么?谢谢.

推荐答案

原来,我应该一直使用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标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆