Flask url_for URLs in Javascript

前端 未结 8 2093
粉色の甜心
粉色の甜心 2021-01-30 10:54

What is the recommended way to create dynamic URLs in Javascript files when using flask? In the jinja2 templates and within the python views url_for is used, what i

8条回答
  •  死守一世寂寞
    2021-01-30 11:05

    Was searching for a solution, them come up with this solution where

    • No add-on is required

    • No hard-coding URL

    The key is to realise Jinja2 has the ability to render javascript out of the box.


    Setup your template folder to something like below:

    /template
        /html
            /index.html
        /js
            /index.js
    

    In your views.py

    @app.route("/index_js")
    def index_js():
        render_template("/js/index.js")
    

    Now instead of serving the javascript from your static folder. You would use:

    
    

    After all, you are generating the javascript on the fly, it is no longer a static file.


    Now, inside of you javascript file, simply use the url_for as you would in any html file.

    For example using Jquery to make an Ajax request

    $.ajax({
      url: {{ url_for('endpoint_to_resource') }},
      method: "GET",
      success: call_back()
    })
    

提交回复
热议问题