>  Q&A  >  본문

python - flask 中的 template_rendered 函数

一个 Flask 初学者的疑问。

大家都知道在 Flask 中我们可以通过 render_template 函数来实现渲染模板。在学习过程中意外发现 Flask 下包含了一个与其命名非常相似的 template_rendered 函数。十分的好奇,查了一下文档,文档是这么写的:

flask.template_rendered

This signal is sent when a template was successfully rendered.
The signal is invoked with the instance of the template as template and the context as dictionary (named context).

看来应该是在模板成功渲染后返回一个字典。
但是文档里写的具体使用场景我不是非常理解,所以想请教各位一下,究竟这个函数应在什么情况下使用,该怎么使用呢?

from flask import template_rendered
from contextlib import contextmanager

@contextmanager
def captured_templates(app):
    recorded = []
    def record(sender, template, context, **extra):
        recorded.append((template, context))
    template_rendered.connect(record, app)
    try:
        yield recorded
    finally:
        template_rendered.disconnect(record, app)
PHP中文网PHP中文网2741일 전556

모든 응답(2)나는 대답할 것이다

  • 阿神

    阿神2017-04-18 09:43:06

    템플릿이 렌더링될 때마다 실행되는 신호입니다. 이 신호를 구독하여 반환되는 값을 얻을 수 있습니다.
    ps: 디버깅 외에는 어떤 상황에서 사용될지 생각이 안 나네요.

    회신하다
    0
  • PHPz

    PHPz2017-04-18 09:43:06

    template_rendered 시그널은 Flask의 핵심 시그널입니다.

    이 신호는 템플릿이 성공적으로 렌더링되면 전송됩니다. 이 신호는 템플릿 인스턴스 템플릿과 컨텍스트 사전(context라는 이름)을 사용하여 호출됩니다.

    이 블로그에서는 구체적인 지침을 제공합니다 https://segmentfault.com/a/11...

    회신하다
    0
  • 취소회신하다