Python Flask Render Text from Variable like render_template

前端 未结 4 1068
灰色年华
灰色年华 2020-11-29 10:28

I know the flask function render_template. I have to give the file name of the template. But now I want to render the string of a template (that is the content

相关标签:
4条回答
  • 2020-11-29 10:33

    You can use render_template_string:

    >>> from flask import render_template_string
    >>> render_template_string('hello {{ what }}', what='world')
    'hello world'
    
    0 讨论(0)
  • 2020-11-29 10:46

    you can use from_string

    template = "text {{ hello }}"
    print app.jinja_env.from_string(template).render(hello='Hello')
    
    >> text Hello
    
    0 讨论(0)
  • 2020-11-29 10:48

    Actually you can call jinja2 render function directly:

    jinja2.Template("I am {{ var }}").render(**kargs)
    

    When not working with flask, this is useful

    0 讨论(0)
  • 2020-11-29 10:51

    Taken from What's the easiest way to escape HTML in Python.

    import cgi
    rendered = render_template('template.html')
    return cgi.escape(rendered)
    
    0 讨论(0)
提交回复
热议问题