简体   繁体   English

Flask url_for Javascript 中的 URL

[英]Flask url_for URLs in Javascript

What is the recommended way to create dynamic URLs in Javascript files when using flask?使用 Flask 时在 Javascript 文件中创建动态 URL 的推荐方法是什么? In the jinja2 templates and within the python views url_for is used, what is the recommended way to do this in .js files?在 jinja2 模板和 python 视图中使用url_for ,在.js文件中推荐的方法是什么? Since they are not interpreted by the template engine.因为它们不被模板引擎解释。

What basically want to do is:基本上想做的是:

// in comments.js
$.post(url_for('comment.comment_reply'));

Which is not possible.这是不可能的。

But naturally, I can execute that in a template:但很自然地,我可以在模板中执行它:

<script>
    $.post(url_for('comment.comment_reply'));
</script>

What @dumbmatter's suggesting is pretty much considered a de facto standard way. @ dumbmatter的建议几乎被认为是事实上的标准方式。 But I thought there would be a nicer way of doing it. 但我认为会有更好的方法。 So I managed to develop this plugin: Flask-JSGlue . 所以我设法开发了这个插件: Flask-JSGlue

After adding {{ JSGlue.include() }} , you can do the following in your source code: 添加{{ JSGlue.include() }} ,您可以在源代码中执行以下操作:

<script>
    $.post(Flask.url_for('comment.comment_reply', {article_id: 3}));
</script>

or: 要么:

<script>
    location.href = Flask.url_for('index', {});
</script>

The Flask documentation suggests using url_for in your HTML file to set a variable containing the root URL that you can access elsewhere. Flask文档建议在HTML文件中使用url_for来设置包含您可以在其他地方访问的根URL的变量。 Then, you would have to manually build the view URLs on top of that, although I guess you could store them similar to the root URL. 然后,您必须手动构建视图URL,尽管我猜您可以将它们存储为类似于根URL。

@ jeremy的答案是正确的,可能是更常见的方法,但作为替代答案,请注意dantezhu编写并发布了一个烧瓶扩展 ,声称在评论中建议进行精确的url-route-map-to-javascript翻译。

I use this dirty and ugly trick: 我使用这个肮脏和丑陋的技巧:

"{{url_for('mypage', name=metadata.name,scale=93,group=2)}}"
.replace('93/group',scale+'/group')

where scale is the javascript variable I want to use for an AJAX request. 其中scale是我想用于AJAX请求的javascript变量。 So, url_for generate an URL and JavaScript replace the parameter at runtime. 因此,url_for生成一个URL,JavaScript在运行时替换该参数。 The generated code is something like: 生成的代码类似于:

"/ajaxservive/mynam/scale/93/group/2".replace('93/group',scale+'/group')

which is pretty strange, but still can't find more elegant solutions. 这很奇怪,但仍然找不到更优雅的解决方案。

In fact, looking at the code of the linked flask extension, it does the same thing but managing the general case. 事实上, 查看链接烧瓶扩展的代码 ,它可以做同样的事情,但管理一般情况。

Was searching for a solution, them come up with this solution where 正在寻找解决方案,他们想出了这个解决方案

  • No add-on is required 不需要加载项

  • No hard-coding URL 没有硬编码的URL

The key is to realise Jinja2 has the ability to render javascript out of the box. 关键是要实现Jinja2能够开箱即用的javascript。


Setup your template folder to something like below: 将模板文件夹设置为如下所示:

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

In your views.py 在你的views.py中

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

Now instead of serving the javascript from your static folder. 现在,而不是从静态文件夹中提供javascript。 You would use: 你会用:

<script src="{{ url_for('index_js') }}"></script>

After all, you are generating the javascript on the fly, it is no longer a static file. 毕竟,你正在生成javascript,它不再是一个静态文件。


Now, inside of you javascript file, simply use the url_for as you would in any html file. 现在,在你的javascript文件里面,只需像在任何html文件中那样使用url_for

For example using Jquery to make an Ajax request 例如,使用Jquery发出Ajax请求

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

In my case, I was trying to dynamically create urls 就我而言,我试图动态创建网址

I solved my issue as follows (Note: I've swapped out Angular's syntax to {[x]}: 我解决了我的问题如下(注意:我已将Angular的语法换成{[x]}:

<ul>
    <li ng-repeat="x in projects">
        {[x.title]}
        {% set url = url_for('static',filename="img/") %}

        <img src="{{url}}{[x.img]}">
    </li>
</ul>

I was able to pass a dynamically created url route to a javascript function by using "tojson" with Jinja2 and Flask.通过在 Jinja2 和 Flask 中使用“tojson”,我能够将动态创建的 url 路由传递给 javascript 函数。

To pass the dynmaic url from the html template to js, simply add '|tojson' at the end of your jinja statment to convert it to the appropriate format.要将动态 url 从 html 模板传递给 js,只需在 jinja 语句的末尾添加“|tojson”即可将其转换为适当的格式。

Instead of:代替:

<script>
 $.post(url_for('comment.comment_reply'));
</script>

Try:尝试:

<script>
 var route = {{ url_for('comment.comment_reply')|tojson }};
 yourJavaScriptFunction(route);
</script>

Then you will be able to use the route in your js functions as the correct route for whatever you need.然后,您将能够使用 js 函数中的路由作为您需要的任何正确路由。

yourJavaScriptFunction(route){
 console.log(route);
}

I was trying to call a FLASK route when a button is pressed. 当按下按钮时,我试图调用FLASK路线。 It should collect the response and update a div. 它应该收集响应并更新div。 The page should not reload. 该页面不应重新加载。

I used jquery to do this. 我使用jquery来做到这一点。

Here's the code: 这是代码:

@app.route('/<name>')
def getContent(name):
    return 'This is %s' % name

HTML: HTML:

    <div id="mySpace" class="my-3">Count</div>

    <button id="next_id" class="btn btn-primary">Press</button>

    <script>
        $('#next_id').click(function (){
            $.get('/aroy', function(data, status){
            $('#mySpace').html(data);
        });
        });
    </script>

I suggest this: 我建议这个:

<script src="{{ url_for('static', filename='js/jquery.js') }}" type="text/javascript">
</script>

Works fine for me 对我来说很好

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM