Flask url_for Javascript中的URL [英] Flask url_for URLs in Javascript

查看:117
本文介绍了Flask url_for Javascript中的URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用flask时,在Javascript文件中创建动态URL的推荐方法是什么?在jinja2模板和python视图中,使用url_for,在.js文件中执行此操作的推荐方法是什么?由于模板引擎无法解释它们.

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 is the recommended way to do this in .js files? Since they are not interpreted by the template engine.

基本上想做的是:

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

这不可能.

但是自然地,我可以在模板中执行该操作:

But naturally, I can execute that in a template:

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

推荐答案

@dumbmatter的建议几乎被认为是事实上的标准方法.但是我认为会有更好的方法.因此,我设法开发了此插件: Flask-JSGlue .

What @dumbmatter's suggesting is pretty much considered a de facto standard way. But I thought there would be a nicer way of doing it. So I managed to develop this plugin: Flask-JSGlue.

添加{{ JSGlue.include() }}后,您可以在源代码中执行以下操作:

After adding {{ JSGlue.include() }}, you can do the following in your source code:

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

或:

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

这篇关于Flask url_for Javascript中的URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆