【问题标题】:Tornado template call include using variableTornado 模板调用包括使用变量
【发布时间】:2020-03-05 10:00:20
【问题描述】:

我正在尝试使用 tornado 模板动态包含 html 页面

{% set tab = (handler.request.arguments).get("tab",[b"input"])[0].decode('utf-8') %}
{% set page_path =  "{}.html".format(tab) %}
{% include page_path %}

但不知何故,这会引发错误:

FileNotFoundError: [Errno 2] No such file or directory: '/home/usr/Data/app/static/html/page_path'

我也试过

{% include {{page_path}} %}

这也会引发错误:

FileNotFoundError: [Errno 2] No such file or directory: '/home/usr/Data/app/static/html/{{page_path}}'

有没有办法在tornado模板中动态使用变量?

【问题讨论】:

    标签: python templates tornado


    【解决方案1】:

    根据 Tornado 文档,可以使用这个:

    ``{% module *expr* %}``
        Renders a `~tornado.web.UIModule`.  The output of the ``UIModule`` is
        not escaped::
    
            {% module Template("foo.html", arg=42) %}
    
        ``UIModules`` are a feature of the `tornado.web.RequestHandler`
        class (and specifically its ``render`` method) and will not work
        when the template system is used on its own in other contexts.
    

    所以使用这个 sn-p 将支持使用变量的龙卷风模板:

    {% set tab = (handler.request.arguments).get("tab",[b"input"])[0].decode('utf-8') %}
    {% set page_path =  "{}.html".format(tab) %}
    {% module Template(page_path) %}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-09
      • 2011-11-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多