问题描述
我想使用Json输出将Bokeh图嵌入Django模板中。
Json输出已准备好在数据库中查询。 情节应呈现给具有特定ID的div。
文档说要在具有以下代码功能的模板中使用Json输出:
item = JSON.parse(item_text);
Bokeh.embed.embed_item(item);
请告知在模板中使用的正确语法:
<div id="title"></div>
<script>
function(response) { return item = JSON.parse( {{plot_json}} ); }
function(item) { Bokeh.embed.embed_item(item); }
</script>
查看文件:
def home(request):
plot_json = Price_Charts.objects.using('llweb').values('timeframe_1h').filter(symbol_pair='ETH')
context = {
'plot_json': plot_json
}
return render(request, "home.html", context)
1楼
Scott Skiles
0
2019-02-25 12:31:14
我对Bokeh不太了解,但是我知道您需要确保JSON对象在Django模板中以JavaScript正确读取并且不会自动转义。 给与背景虚化“一起一试 ”语法。
<div id="title"></div>
<script>
fetch('/plot')
.then(function(response) {
{% autoescape off %}
return item = JSON.parse( {{plot_json}} );
{% autoescape on %}
})
.then(function(item) { Bokeh.embed.embed_item(item); })
</script>
2楼
Tony
0
2019-02-27 10:03:40
也许这个简化的jinja2示例可以为您提供帮助(在Bokeh v1.0.4上进行了测试)。 运行为:
python myapp.py
文件和目录结构:
myapp
|
+---myapp.py
+---templates
+---index.html
myapp.py
import io
import json
import jinja2
import numpy as np
from bokeh.plotting import figure, curdoc
from bokeh.embed import json_item
from bokeh.resources import CDN
plot = figure()
plot.line(np.arange(10), np.random.random(10))
curdoc().add_root(plot)
renderer = jinja2.Environment(loader = jinja2.FileSystemLoader(['templates']), trim_blocks = True)
html = renderer.get_template('index.html').render(resources = CDN.render(), item_json_object = json.dumps(json_item(plot)))
filename = 'json_items.html'
with io.open(filename, mode = 'w', encoding = 'utf-8') as f:
f.write(html)
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
{{ resources }}
</head>
<body>
<div id="myplot"></div>
<script>
Bokeh.embed.embed_item({{ item_json_object }}, "myplot");
</script>
</body>
</html>
传递给模板的json.dumps(json_item(plot)
)的结果似乎已经是一个JSON对象,因此您不能在其上使用JSON.parse()
。
或确保您确实将字符串对象传递给此函数。
您所引用的指向了与此不同 , 意义上是在浏览器页面加载时使用JS fetch()方法动态加载地块数据,而此处的地块数据是在模板渲染时附加到页面的时间。