Flask | Jinjia2 | Javascript:将Flask模板变量传递到Javascript中 [英] Flask|Jinjia2|Javascript: Passing Flask template variable into Javascript

查看:106
本文介绍了Flask | Jinjia2 | Javascript:将Flask模板变量传递到Javascript中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将变量从Flask模板传递到Javascript文件的最佳方法是什么?这是我的代码

What is the best way to pass a variable from a Flask template into the Javascript file? Here is my code

我的Web应用程序中有一个简单的视图:

I have a simple view in my webapp:

@webapp.route('/bars')
def plot_d3_bars():
  return render_template("bars.html", calendarMap = calendarMap)

我有一个模板化的HTML文件,如下所示:

I have a templated HTML file that looks like this:

{% extends "base.html" %}

{% block title %} Bar View {% endblock %}

{% block content %}

{% with calendarMap=calendarMap %}
    {% include "buttons.html" %}
{% endwith %}

<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<script src="/static/css/d3.tip.v0.6.3.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>

<!-- Custom codes for d3 plotting -->
<link href="/static/css/bars.css" rel="stylesheet">
<script> var calendarMap = {{ calendarMap|tojson }}; </script>
<script src="/static/bars.js"></script>

{% endblock %}

先前的答案告诉我,我可以将变量json化为JSON对象,然后就可以使用它了.但是,我想在bars.js内使用calendarMap吗?但是我遇到了一些范围界定问题(例如,bars.js无法识别此calendarMap),该怎么办?

Previous answers told me that I could just jsonify the variable into a JSON object and I'll be able to use it. However, I want to use calendarMap inside of bars.js? but I am running into some scoping problems (i.e. bars.js doesn't recognized this calendarMap), what should I do instead?

推荐答案

好吧,也许为时已晚,但是我们开始吧.

Well, maybe it is too late, but here we go.

当您使用嵌入在HTML代码中的JavaScript代码时,此脚本将与HTML一起呈现.因此,在JavaScript中引用的任何变量(例如Flask变量)都将在呈现的页面中提供.

When you use a JavaScript code embedded in HTML code, this script will be rendered together with HTML. So any variable referenced in JavaScript, as a Flask variable, will be available in the page rendered.

当您使用以HTML代码链接的外部JavaScript文件时,在呈现HTML之前,该文件的代码已经存在.在某些情况下,我可能会说大多数,您不是此文件的所有者.因此,JS文件中引用的任何变量都不会呈现.

When you use an external JavaScript file linked in HTML code, its code already exists, before the HTML be rendered. In some cases, I may say most of them, you aren't the owner of this file. So any variable referenced in JS file will not be rendered.

您可以通过JS代码将此变量放入HTML中,并使用来自外部JS文件的函数来使用此数据.

You may put this variable in HTML, via JS code, and consume this data with functions from foreign JS file.

或者您可以在渲染模板之前使用此JS文件.但是我强烈建议不要使用这种方法.

Or you can render this JS file, before render the template, and use it. But I strongly recomend not to use this approach.

这篇关于Flask | Jinjia2 | Javascript:将Flask模板变量传递到Javascript中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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