在龙卷风中生成全局变量的处理程序

handler to generate global variables in tornado

我的 Web 应用程序中有一个所有页面通用的顶部栏。其代码位于一个名为 base.html 的单独 html 文件中,该文件包含在所有其他页面中(例如 sample.html)。现在,我想在 base.html 中加载一个变量 'notifications'。如果可能,我想使用单独的处理程序来为 base.html 生成通知。但是,目前,据我所知,我必须调用 def 来从我 write/have 编写的每个页面处理程序生成它并将其传递。有没有更简洁的方法来做到这一点,我不必更改其他页面处理程序?对不起,如果这是一个愚蠢的问题。我对龙卷风还很陌生。

base.html

// some html 
{{ notifications  }}


sample.html

{% extends base.html %}

// some html

方法是使用 UIModule。创建一个 UIModule 的子类,它定义了一个 render 方法,在 ui_modules dict 中将它传递给 Application 构造函数(ui_modules=dict(Notifications=NotificationsModule)),然后你可以调用它在您的模板中 {% module Notifications() %}