Getting a request parameter in Jinja2

后端 未结 4 1398
猫巷女王i
猫巷女王i 2021-01-31 15:53

How can I retrieve a request param a in Jinja2 template?

http://foo.bar?a=1
4条回答
  •  生来不讨喜
    2021-01-31 16:21

    You will need to pass this information to your jinja2 templates, since it is just a templating engine, and not the web framework.

    The "view generation" part of your web framework that deals with requests will usually be passed some HTTP request header information or data structure. this often includes the request params. If it does, then you can just pass this to your template.

    Even if the header info you get doesn't include the request params, it will always include the url. Once you have the url in your view function code, you can do something like this:

    url = "http://foo.bar?a=1&b=2&c=true" # actually get this from your http request header
    import urlparse
    split_result = urlparse.urlsplit(url)
    request_params = dict(urlparse.parse_qsl(split_result.query))
    # request_params = {'a': '1', 'b': '2', 'c': 'true'}
    

    Then you can send this request_params dictionary to your jinja template.

提交回复
热议问题