1

I have a string that I want to treat as a Jinja template. I tried returning the string, but it gets sent as is, Jinja doesn't render it. I do not want to make a template file to render it with render_template. How can I render the string with Jinja?

@app.route('/results')
def results():
    template = '''<div class="results">
        {% for option in options() %}
            <p>{{ option }}</p>
        {% endfor %}
    </div>
    '''
    return template
davidism
  • 121,510
  • 29
  • 395
  • 339
glls
  • 2,325
  • 1
  • 22
  • 39
  • 2
    What "templating function" are you expecting to "kick in" here? You return a raw string, so that's what is sent to the client. – Daniel Roseman May 20 '16 at 08:45
  • maybe i should change my question to, "how to render a raw string as html"? – glls May 20 '16 at 08:51
  • Still don't understand what you're asking. What are you seeing on the browser, and how does this differ from what you're expecting to see? – Daniel Roseman May 20 '16 at 08:59

1 Answers1

5

You are looking for render_template_string.

flask.render_template_string(source, **context)

Renders a template from the given template source string with the given context.

Parameters:

  • source – the sourcecode of the template to be rendered
  • context – the variables that should be available in the context of the template.
from flask import render_template_string

Call it on your HTML string to render it, and return the result.

return render_template_string(template)
davidism
  • 121,510
  • 29
  • 395
  • 339
Khopa
  • 2,062
  • 1
  • 23
  • 22