简体   繁体   English

如何访问从 Python flask 路由中提供给 HTML 模板的数据?

[英]How can I access data provided to HTML template from Python flask routing in my JavaScript code?

So I have a python flask application that routes to a site and passes along two lists:所以我有一个 python flask 应用程序,它路由到一个站点并传递两个列表:

def chart():
    labels = ['x', 'y', 'z']
    values = [100, 150, 100]
    return render_template('chart.html',
     labels=labels, values=values)

I use Chart.min.js and I can then use the lists in rendering a graph in my chart.html :我使用Chart.min.js ,然后可以使用列表在我的chart.html中呈现图形:

{% block body %}
<h1>Test chart</h1>

<canvas id="myChart" width="800" height="400"></canvas>

<p id="caption">chart displaying labels n' values</p>

<script type=text/javascript>

    var ctx = document.getElementById('myChart');

    var names = [
        {% for item in labels %}
            "{{ item }}",
        {% endfor %}
    ];

    var numbers = [
        {% for item in values %}
            {{ item }},
        {% endfor %}
    ];

    var chartData = {
        labels: names,
        datasets: [{
          label: 'values',
           data: numbers
        }]
    };

    var myChart = new Chart(ctx, {
        type: 'line',
        data: chartData
    });

</script>

{% endblock %}

Now this works fine and I get a nice pretty graph.现在这工作正常,我得到了一个漂亮的图表。 Then I wanted to put my JavaScript in a seperate file in the static folder for my flask application but I cannot find how I'm supposed to access the lists passed along to chart.htlm .然后我想将我的 JavaScript 放在 static 文件夹中的一个单独文件中,用于我的chart.htlm应用程序,但我找不到我应该如何访问列表。 I can render a graph just fine if I hardcode some data into the JS file but I can't seem to get the data provided by the python code..如果我将一些数据硬编码到 JS 文件中,我可以很好地渲染图表,但我似乎无法获得 python 代码提供的数据。

var ctx = document.getElementById('myChart');

// var names = ['x', 'y', 'z'];
// var numbers = [100, 150, 100];

var chartData = {
    labels: names,
    datasets: [{
        label: 'values',
        data: numbers
    }]
};

var myChart = new Chart(ctx, {
    type: 'line',
    data: chartData
});

I have tried to loop the contents of the lists from my python file into different containers such as <div> , <ol> and <ul> and access those through document.getElementById("") among some other attempts, can't really remember them all.我试图将列表的内容从我的 python 文件循环到不同的容器中,例如<div><ol><ul>并通过document.getElementById("")访问它们以及其他一些尝试,真的不能记住他们。

I have tried to find the answer on google but to no avail.我试图在谷歌上找到答案,但无济于事。

Any help is appreciated and I should mention that I'm new to these coding languages and frameworks so please have some oversight if what I am missing is obvious.感谢您提供任何帮助,我应该提一下,我是这些编码语言和框架的新手,所以如果我缺少的东西很明显,请进行一些监督。

=== NEW WORKING VERSION === === 新工作版本 ===

chart.html : chart.html

<script type="text/javascript">

    window.addEventListener('DOMContentLoaded', (event) => {
        const myChart2 = document.getElementById('ChartOne');
        drawChart(ChartOne, {{ labels| tojson }}, {{ values| tojson }}, ChartType.LINE);

    });

</script>

<div>
    <canvas id="ChartOne" width="800" height="400"></canvas>
    <p id="caption">line chart displaying labels n' values</p>
</div>

script.js : script.js

const ChartType = {
    LINE: "line" // add more variables for more chart options
}

function drawEmployeeChart(ctx, labels, values, chartType) {
    var chartData = {
        labels: labels,
        datasets: [{
            label: 'values',
            data: values,
        }]
    };

    var myChart = new Chart(ctx, {
        type: chartType,
        data: chartData
    });
}

Now that you've separated your javascript into a new js file, you have to get your variables there.现在您已将 javascript 分离到一个新的 js 文件中,您必须将变量放在那里。

What you could do is define a javascript function in your.js file that takes two arrays:你可以做的是在你的.js文件中定义一个javascript function,它需要两个arrays:

function render_chart(labels, values)
{
    var ctx = document.getElementById('myChart');

    var chartData = {
        labels: names,
        datasets: [{
            label: 'values',
            data: values
        }]
    };

    var myChart = new Chart(ctx, {
        type: 'line',
        data: chartData
    });
}

Then call the function from your chart.html page, but you have to convert the variables you pass from Flask to json.然后从您的图表中调用chart.html页面,但是您必须将从 Flask 传递的变量转换为 Z4566DEEC7F6ECDF25 To do that do this, using the special tojson Jinja2 filters:为此,请使用特殊的tojson Jinja2 过滤器:

<script type="text/javascript">render_chart({{ labels|tojson }}, {{ values|tojson }})'></script>

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

相关问题 如何在模板中将数据从 Flask 传递到 JavaScript? - How can I pass data from Flask to JavaScript in a template? 如何在 javascript 代码中访问从服务器发送的数据(使用烧瓶)? - how to access the data sent from server(using flask), in javascript code? 如何在PyQT 5.7中从JavaScript访问Python代码? - How can I access Python code from JavaScript in PyQT 5.7? 如何使用 Javascript 中的 Fetch API 将字符串中的 HTML 中的 XML 发送到 Python(使用 Flask) - How can I send a XML from HTML in string to Python (using Flask) using Fetch API in Javascript 如何在 HTML 上的 javascript 上从 Flask 打印数组元素 - How can I print element of array from Flask on javascript on HTML 如何将变量从 Python Flask 转移到 JavaScript? - How can I transfer a variable from Python Flask to JavaScript? 如何将Json数据从javaScript发送到Flask - How can I send Json Data from javaScript to Flask 如何将数据从 Flask 发送到 JavaScript? - How I can send data from Flask to JavaScript? 如何在 HTML 和 Javascript 的帮助下从浏览器使用 python (Django) 访问我的网络摄像头? - How do i access my webcam with python (Django) from the browser with the help of HTML and Javascript? 如何在NodeWebkit中的html代码中从节点模块访问刮取的数据 - How do I access the scraped data from node module in my html code in NodeWebkit
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM