Django,用于将Javascript插入模板的语法

问题描述 投票:0回答:2

我想使用Json输出在Django模板中嵌入Bokeh图。 http://bokeh.pydata.org/en/latest/docs/user_guide/embed.html#json-items

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)
javascript django bokeh
2个回答
0
投票

我对Bokeh了解不多,但我知道你需要确保在Django模板中正确读取JSON对象为JavaScript而不是自动转义。给autoescape off一起尝试以及Bokeh'then'语法。

<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>

0
投票

也许这个简化的jinja2示例可以帮助您(在Bokeh v1.0.4上测试)。运行方式为:

python myapp.py

文件和目录结构:

myapp
   |
   +---myapp.py
   +---templates
        +---index.html 

没有app.朋友

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()。或者确保您确实将字符串对象传递给此函数。

你引用的Bokeh documentation指向an example,它与这个不同,在某种意义上,绘图数据是在浏览器的页面加载时使用JS fetch()方法动态加载的,而这里的绘图数据在模板渲染时附加到页面。

© www.soinside.com 2019 - 2024. All rights reserved.