Search code examples
pythonflaskjinja2keyword-argument

how to consume kwargs from flask in jinja


From a jinja html file, I want to consume & print the kwargs passed from python/flask. I pass variables into flask render_template, however, I can't figure out how to get the kwargs from jinja. This is a minimal flask example:

from flask import Flask, render_template, request

app = Flask(__name__)    
@app.route("/foo", methods=['POST'])
def foo():
    return render_template("mypage.html", alpha=request.form.get('alpha'),
            beta=request.form.get('beta'))

This is the jinja html file mypage.html:

<html><body><ul>
    {% for k, v in kwargs.items() %}
        <li>{{ k }}{{ v }}</li>
    {% endfor %}
</ul></body></html>

This is the error when I try to post to the page:

File "/usr/lib/python3.8/site-packages/jinja2/environment.py", line 430, in getattr
return getattr(obj, attribute)
jinja2.exceptions.UndefinedError: 'kwargs' is undefined

Very sorry if this is a duplicate, but I can't find this question/answer anywhere.


Solution

  • your program needs to match template's kwargs:

    from flask import Flask, render_template, request
    
    app = Flask(__name__)    
    @app.route("/foo", methods=['POST'])
    def foo():
        kwargs = {'alpha': request.form.get('alpha'),
                  'beta': request.form.get('beta'),
                 }
        return render_template("mypage.html", kwargs=kwargs)