【问题标题】:Flask - use jinja macros without a templateFlask - 在没有模板的情况下使用 jinja 宏
【发布时间】:2021-06-20 11:00:53
【问题描述】:

我有一个如下所示的 Flask 应用程序:

@app.route('/')
def index():
    headline = render_template('headline.html', headline = 'xyz') #-> return <h1>xyz</h1>
    return render_template('page.html', headline = headline) # insert headline html into a page

headline.html 是一个从宏文件 (macros.html) 中导入 jinja 宏的模板。宏生成标题。

headline.html:

{% import 'macros.html' as macros %}
{{ macros.get_headline(headline) }}

macros.html:

{% macro get_headline(headline) %}
<h1>{{ healine }}</h1>
{% endmacro %}

我的问题是——是否可以调用宏来获取headline无需调用模板headline.html

理想情况下,我想看看

@app.route('/')
def index():
    headline = # somehow call get_headline('xyz') from macros.html
    return render_template('page.html', headline = headline) # insert headline html into a page

【问题讨论】:

    标签: python flask jinja2


    【解决方案1】:

    您可以从字符串中渲染模板,而不是从文件中渲染模板。所以你可以从一个字符串中调用你的宏。

    from flask.templating import render_template_string
    
    @app.route('/')
    def index():
        headline = render_template_string(
            "{% import 'macros.html' as macros %}"
            "{{ macros.get_headline(headline) }}",
            headline='xyz'
        )
        return render_template('page.html', headline=headline)
    

    (忽略macros.html中的拼写错误healine而不是headline

    【讨论】:

      【解决方案2】:

      我的问题是——是否可以调用宏来获取headline无需调用模板headline.html

      我希望你弄清楚你的情况。我敢打赌,你最终会找到比你提议的更好的方法来做到这一点,这对我来说似乎有点倒退,但是嘿,这是学习过程的一部分!

      特别是对于仅采用单个参数的简单文本转换函数,您可能会从使用Environment.filters 注册为 Jinja 过滤器的 Python 函数获得更好的效果,如here 所述。它的语法更少,您可以以标准方式使用 Python Jinja 模板中的相同函数,而无需 hack。

      也就是说,我今天在 Jinja 模板上误入了.module property。它允许您从模板调用宏作为常规 Python 函数:

      macros.html:

      {% macro get_headline(headline) -%}
      <h1>{{ headline }}</h1>
      {%- endmacro %}
      

      test.py:

      # these imports not needed for a Flask app
      from jinja2 import Environment, FileSystemLoader
      
      # just use `app.jinja_env` for a Flask app
      e = Environment(loader=FileSystemLoader('.'))
      t = e.get_template('macros.html')
      
      t.module.get_headline('Headline')
      # >>> '<h1>Headline</h1>'
      

      我相信(?)这可以满足您最初的要求,使用 Flask 已有的 app.jinja_env 环境,并且没有额外的导入。

      【讨论】:

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