【问题标题】:Flask / Jinja - render user input jinja template inside parent template with scope/context from parentFlask / Jinja - 在父模板中渲染用户输入 jinja 模板,其范围/上下文来自父
【发布时间】:2016-06-04 21:44:40
【问题描述】:

标题一团糟,所以让我尽可能清楚。如何实现do_magic

在这个template.html中

{% set x = 1 %}
{{ do_magic(subtemplate) }}, {{ x }}, {{ y }}

从此方法调用

@app.route('/')
def home():
  return render_template(
    'template.html',
    subtemplate='{{ x }}, {{ y }}',
    y=2,
    do_magic=do_magic
  )

def do_magic(some_text):
    ... # what goes here?

应该输出这个

1, 2, 1, 2

不是这个

{{ x }}, {{ y }}, 1, 2

【问题讨论】:

  • 你试过{% include subtemplate %}吗?
  • @jonrsharpe 不会尝试通过文件名包含模板吗?我需要从原始字符串模板中包含,而不是它的文件名。我需要从 python 函数而不是 jinja 代码中完成。
  • ...为什么?你能举一个不那么抽象的例子吗?将函数传入以从模板中的某些状态和代码中的某些状态进行回调似乎有点倒退。是什么让这变得必要?
  • @jonrsharpe 我将内容(子模板)存储在我的数据库中。注册过滤器 (do_magic) 使用 div 包装在所见即所得编辑器中创建的内容,该 div 具有一个类,允许通用脚本查找站点的所见即所得创建部分并在客户端改进一些东西,因为它会是一个pita 在服务器端或 WYSIWYG 编辑器中进行。一切正常,除了现在我想在 WYSIWYG 编辑器中输入一个变量的名称,并在页面渲染时将其替换为同名的 jinja 变量。

标签: python flask jinja2


【解决方案1】:

我想我明白了!

from jinja2 import contextfunction, Markup

@contextfunction
def do_magic(context, subtemplate):
  ''' Renders string subtemplate with variables from the active context. '''
  template_object = app.jinja_env.from_string(subtemplate)
  html = template_object.render(**context)
  return Markup(html)

我当然希望这不会有某种我不知道的致命缺陷。

(顺便说一句,你们看到 Jinja 源代码了吗?它从模板构建 python 脚本,然后运行 ​​python 脚本!)

编辑

事实证明,特设的 WYSIWYG 编辑器不能很好地处理复杂的 jinja 模板,而且回想起来,我认为我永远不需要一个到处都有一堆 if-else 的 CMS。

我想我真正想要的只是替换变量的基本模板功能。所以我做了一个方法来用正则表达式替换变量。

import re
from jinja2 import contextfunction, Markup

@contextfunction
def do_magic(context, subtemplate):
  fallback_value = '???'
  def get_replacement(matchobj):
    key = matchobj.group(1)
    return context.get(key, fallback_value)
        
  pattern = r'{{\s*([a-zA-Z0-9_]+)\s*}}'
  html = re.sub(pattern, get_replacement, subtemplate)
  return Markup(html)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-11-24
    • 1970-01-01
    • 2015-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-20
    相关资源
    最近更新 更多