gpt4 book ai didi

javascript - python 瓶 : Assigning a python variable to Javascript variable

转载 作者:行者123 更新时间:2023-12-02 16:42:44 26 4
gpt4 key购买 nike

我正在使用Bottle用于渲染网页的 Web 框架。我使用 Bottle 模板引擎从 Python 传递变量,然后在嵌入了 Python 代码的模板文件中对它们进行相应的处理。

现在,当我在模板中使用 javascript 时,问题就出现了。如果我尝试在 javascript 函数中访问我的 Python 变量,则会失败并显示 TypeError: unhashable type: 'list'

我在 python 文件中调用我的模板:

list_vals = [['Mushrooms', 3, 5], ['Onions', 1, 4], ['Olives', 1, 5], ['Zucchini', 1, 2]]    
return bottle.template(os.path.join(os.path.dirname(__file__), 'templates', 'pizzaStats.html'), vals=list_vals)

在我的模板文件中,我当前使用 vals 变量仅在 JavaScript 内打印,如下所示(仅显示模板的脚本部分):

<script type="text/javascript">

// Load the Visualization API and the piechart package.
google.load('visualization', '1.0', {'packages':['corechart']});

// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);

// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
function drawChart() {

// Create the data table.
var data = new google.visualization.DataTable();
%print ({{ vals }})
var graphdata = {{ vals }};
data.addColumn('string', 'Topping');
data.addColumn('number', 'Slices');
data.addColumn('number', 'pieces');
data.addRows(graphdata);

// Set chart options
// to smoothen the lines - 'curveType':'function'
var options = {'title':'How Much Pizza I Ate Last Night',
'width':400,
'height':300};

// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>

即使我将变量的类型从 list 更改为 dict 类型,它仍然会提示。 TypeError: unhashable type: 'dict' 该错误来自 print() 但如果我删除 print() 则什么也不会发生,也不会绘制了图形,意味着变量未正确分配。

最终目标是将此变量分配给 JavaScript 变量,然后该变量将使用 Google API 绘制图表。将 Python 变量分配给 Bottle 模板内的 javascript 变量的正确方法是什么?谢谢。

最佳答案

我认为问题出在模板端,当您渲染 vals 参数时。渲染的 vals 必须是有效的 JavaScript 代码。默认情况下,bottle 自动转义 HTML 特殊字符,其中包括单引号和双引号。因此,当您将 Python list_vals 列表传递给 template 函数时,它会被计算为如下字符串:

"[['Mushrooms', 3, 5], ['Onions', 1, 4], ['Olives', 1, 5], ['Zucchini', 1, 2]]"

并通过 Bottle 后记自动转义,如下所示:

[[&#039;Mushrooms&#039;, 3, 5], [&#039;Onions&#039;, 1, 4], [&#039;Olives&#039;, 1, 5], [&#039;Zucchini&#039;, 1, 2]]

生成无效的 JavaScript 代码。

快速解决方案可能只是 disabling the bottle auto-escaping只需在模板 vals 参数中添加感叹号即可:

var graphdata = {{!vals}};

关于javascript - python 瓶 : Assigning a python variable to Javascript variable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27373831/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com