class Echarts_html(TemplateView): template_name = "templeate/app01/echarts.html" def get_context_data(self, **kwargs): context = super(Echarts_html, self).get_context_data(**kwargs) aaa= { 'title': { 'text': 'ECharts 入門示例' }, 'tooltip': {}, 'legend': { 'data': ['銷量'] }, 'xAxis': { 'data': [] }, 'yAxis': {}, 'series': [{ 'name': '銷量', 'type': 'bar', 'data': [] }] } articles = Article.objects.all() for item in articles: aaa['xAxis']['data'].append(item.title) aaa['series'][0]['data'].append(item.read_count) context['aaa'] = aaa return context
前臺代碼,數據處理完畢,前臺直接使用。可是記得加{{xxx|safe}} 不然會被轉義(xss跨站了解下)
<body> <!-- 爲ECharts準備一個具有大小(寬高)的Dom --> <div id="main" style="width: 600px;height:400px;"></div> <script type="text/javascript"> // 基於準備好的dom,初始化echarts實例 var myChart = echarts.init(document.getElementById('main')); // 指定圖表的配置項和數據 var option = {{ aaa | safe}}; myChart.setOption(option); </script>
</body>
class Echarts_html(TemplateView): template_name = "templeate/app01/echarts.html" def get_context_data(self, **kwargs): context = super(Echarts_html, self).get_context_data(**kwargs) context['articles'] = Article.objects.all() return context
前臺代碼,js處理,注意的一點就是js中數組push(相似append)必須是字符串或者數字,直接"xxxx"轉成字符串。javascript
<body> <!-- 爲ECharts準備一個具有大小(寬高)的Dom --> <div id="main" style="width: 600px;height:400px;"></div> <script type="text/javascript"> // 基於準備好的dom,初始化echarts實例 var myChart = echarts.init(document.getElementById('main')); // 指定圖表的配置項和數據 var option = { 'title': { 'text': 'ECharts 入門示例' }, 'tooltip': {}, 'legend': { 'data': ['閱讀量'] }, 'xAxis': { 'data': [] }, 'yAxis': {}, 'series': [{ 'name': '閱讀量', 'type': 'bar', 'data': [] }] } {% for item in articles %} option['xAxis']['data'].push("{{ item.title }}") option['series'][0]['data'].push("{{ item.read_count }}") {% endfor %} console.log(option) // 使用剛指定的配置項和數據顯示圖表。 myChart.setOption(option); </script> </body>