Skip to content

Commit

Permalink
Merge pull request #240 from kinegratii/feature_template_function
Browse files Browse the repository at this point in the history
自定义模板
  • Loading branch information
chenjiandongx committed Nov 21, 2017
2 parents 4972f96 + 9f715a6 commit 7620e27
Show file tree
Hide file tree
Showing 26 changed files with 1,573 additions and 208 deletions.
137 changes: 137 additions & 0 deletions docs/en-us/doc_advance_feature.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
# pyecharts document - Advance Uage

This artile describe some new features in V0.3.0.

- Custom Template File
- How to Reference the Javascript file.

## Python Script

### Way I

A chart render proccess can be described as the following table.

| Step | Simple Code | remark |
| --------------------------- | ---------------------------------------- | ------ |
| 1 Create chart instance | `bar = Bar()` | |
| 2 Add the data | `bar.add(**kwargs)` | |
| 3 Create config instance | `config = PyEchartsConfig(**kwargs)` | |
| 4 Build the template engine | `engine = EchartsEnvironment(pyecharts_config=config)` | |
| 5 Load template file | `tpl = engine.get_template('demo_tpl.html')` | |
| 6 Render | `html = tpl.render(bar=bar)` | |
| 7 Write to target file | `write_utf8_html_file('my_demo_chart.html', html)` | |

### Way II

You can also use `render` method of chart class, with is the shortcut of way I.

Step 1:Use `pyecharts.configure` or `pyecharts.online` to config items.

```python
configure(jshost=None, echarts_template_dir=None, force_js_embed=None, **kwargs)
```

Step 2: Call the `render` method to generate HTML file.

the method sigin for simple chart:

```python
Chart.render(path='render.html', template_name='simple_chart.html', object_name='chart', extra_context=None)
```

the method sigin for page:

```python
Page.render(path='render.html', template='simple_page.html', object='page', extra_context=None)
```

Each parameter marod

- path :the file name of target HTML file.
- template_name: the file name of template.
- object_name: the variable name of chart in the template file.
- extra_context: the exra data dictionary.

## Jupyter Notebook

Chart class implement `_repr_html_` interface,You can directly call the instance to show the chart in a cell.



## Flask

It is easy to integrate pyechart and Flask.This is a example.

Step 1: Create server code.

```python
from flask import Flask
from pyecharts.engine import EchartsEnvironment
from pyecharts.conf import PyEchartsConfig

class FlaskEchartsEnvironment(EchartsEnvironment):
def __init__(self, app, **kwargs):
EchartsEnvironment.__init__(self, **kwargs)
self.app = app

class MyFlask(Flask):
jinja_environment = FlaskEchartsEnvironment
jinja_options = {'pyecharts_config': PyEchartsConfig(
jshost='https://cdn.bootcss.com/echarts/3.7.2',
echarts_template_dir='templates'
)}

app = MyFlask(__name__)

@app.route("/")
def hello():
hm = create_heatmap()
return render_template('flask_tpl.html', hm=hm)

def create_heatmap():
begin = datetime.date(2017, 1, 1)
end = datetime.date(2017, 12, 31)
data = [[str(begin + datetime.timedelta(days=i)),
random.randint(1000, 25000)] for i in
range((end - begin).days + 1)]
heatmap = HeatMap("日历热力图示例", "某人 2017 年微信步数情况", width=1100)
heatmap.add("", data, is_calendar_heatmap=True,
visual_text_color='#000', visual_range_text=['', ''],
visual_range=[1000, 25000], calendar_cell_size=['auto', 30],
is_visualmap=True, calendar_date_range="2017",
visual_orient="horizontal", visual_pos="center",
visual_top="80%", is_piecewise=True)
return heatmap


app.run(port=10200)
```

Step 2:Create template file.

```html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>自定义模板</title>
{{ echarts_js_dependencies(hm) }}
</head>
<body>
<p>在 Flask 下使用 echarts_* 系列模板函数(Template Functions)渲染页面。</p>
{{ echarts_container(hm) }}
{{ echarts_js_content(hm) }}
</body>
</html>
```

In the example,the js file of boot CDN is used, so the following code fragment is generate.

The advance of using external link are listed as following:

- Descrease the file size of HTML file
- More easy to integrate with web framework

## Django

Django use its own template engine, see the project [django-echarts](https://github.com/kinegratii/django-echarts) for more detail.
207 changes: 195 additions & 12 deletions docs/en-us/doc_api.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,34 @@
# pyecharts API
pyecharts API

This document describes the public API for *pyecharts* library and it will be read by developers.

## pyecharts Config Items

The class `pyecharts.conf.PyEChartsConfig` contains all config items when using *pyecharts* library.Before building chart, you can use module function `configure` to set all config items.

```python
import pyecharts
pyecharts.configure(P1=V1, P2=V2,...)
```

### Config Item List

**echarts_template_dir**

The diretory of template files. Default value: '.'(current diretory).

**jshost**

The repository of js dependency files.You can set it with a local host url or remote host url(starts with `http://` or `https://` ).

You can also use `pyecharts.online()` to set this item.

WIth the compatibility, this string value do not need `/` as its ending character.

**force_js_embed**

Whether to force to insert javascript file with internal embed mode. This item will affect the function`echarts_js_dependencies` .

## Charts Classes

Charts classes is the core component of this library.Each charts class represents the one kind of chart in [Echarts](http://echarts.baidu.com/) .
Expand All @@ -21,7 +48,6 @@ This table list properties for these chart classes.
| heigth |||||| |
| options |||||| |
| js_dependencies |||||||
| charts | | | | | ||

**chart_id**

Expand All @@ -41,11 +67,7 @@ Data type:dict.The config options for a chart。Each chart has its own format an

**js_dependencies**

Data type:set.The js filename collections for a chart's dependencies.Every element do not contain the filename extension(.js).E.g `{'echarts.min', 'fujian'}`

**charts**

The origin chart list in the class `pyecharts.custom.page.Page` .Each element can be a instance of the subclass of `pyecharts.base.Base` .
Data type:set.The js filename collections for a chart's dependencies.Every element do not contain the filename extension(.js).E.g `{'echarts.min', 'fujian'}` .


### Methods
Expand All @@ -56,11 +78,11 @@ Add options and data to a chart.See the source code for more detail.

| Chart Class | Function Sign |
| ----------- | ---------------------------------------- |
| Base | `add(**echarts_options)` |
| Base | `add(**echarts_options)` |
| Grid | `add(grid_width=None, grid_height=None, grid_top=None, grid_bottom=None, grid_left=None, grid_right=None)` |
| Overlap | `add(chart, xaix_index=0, yaix_index=0, id_add_xaxis=False, is_add_yaxis=False)` |
| Timeline | `add(chart, time_point)` |
| Page | `add(achart_or_charts)` |
| Timeline | `add(chart, time_point)` |
| Page | `add(achart_or_charts)` |

**get_js_dependencies()**

Expand All @@ -78,6 +100,29 @@ Render javascript code fragment including options.

Print all options of charts

## Multiple Chart

`pyecharts.custom.page.Page` is used to show multiple chart in a html page,which includes properties and methods above.

Also, `Page` inherits built-in `list` and len,iter,index,splice,append,extend are supported.

Example,print the option for each chart in a page object.

```python
page = Page()
line = Line('Demo Line')
# ... Add data to line
page.add(line)
kline = KLine('Demo kline')
# ... Add data to kline
page.append(kline)

for chart in page:
chart.show_config()
```



## Data Hanlder Methods

These methods are tool methods for data handlers.
Expand All @@ -99,7 +144,7 @@ print(y) # ['34', '45', '12']

**json_dumps**

`pyecharts.base.json_dumps(data, indent=0)`
`pyecharts.utils.json_dumps(data, indent=0)`

Convert *data* to json string, and add encoding for some specified data type:

Expand All @@ -114,4 +159,142 @@ Convert *data* to json string, and add encoding for some specified data type:

Data type `jinja2.Environment`。pyecharts provides a build-in environment object for rendering using Jinja2 engine。

- This environment use *pyecharts/templates* as its base directory to store HTML and javascript files.
- This environment use *pyecharts/templates* as its base directory to store HTML and javascript files.

## Template Engine

### Overview

*pyecharts* use [Jinja2](http://jinja.pocoo.org/) as its template engine, with some extra template functions.

> *Tempate function* and *template tag* is the same feature in the area of template engine.In Django it is called *template tag* and it is called *template function* in jinja2.
### Engine Class

**EChartsEnvironment**

`pyecharts.engine.EChartsEnvironment`

EChartsEnvironment class inherits `Jinja2.Environment` .

### 模板函数

EChartsEnvironment contains some template functions, which receives a or some `Chart` / `Page` objects.See the following table.

| 标签/调用形式 | F(chart) | F(page) | F(chart1,chart2,...)/F(*page) |
| ----------------------------- | -------- | ------- | ----------------------------- |
| echarts_js_dependencies ||||
| echarts_js_dependencies_embed ||||
| echarts_container || | |
| echarts_js_content ||||
| echarts_js_content_wrap ||||



**echarts_js_dependencies**

`pyecharts.template.echarts_js_dependencies(*args)`

Render script html nodes with internal embed mode or enternal link.The mode will follow this table.

| jshost/force_js_embed | True | False |
| --------------------- | -------------- | -------------- |
| local host | internal embed | internal embed |
| remote host | internal embed | enternal link |

Example

```
# Jinja2 Context function
{{ echarts_js_dependencies('echarts') }}
# Html Output
<script type="text/javascript" src="js/echarts.js"></script>
# Python
bar = Bar('Demo Bar')
# Jinja2 Context function
{{ echarts_js_dependencies(bar) }}
# Html Output
<script type="text/javascript" src="js/echarts.js"></script>
```



**echarts_js_dependencies_embed**

`pyecharts.template.echarts.js_dependencies_embed(*args)`

Render script nodes in internal embed mode.Only support local host.

**echarts_container**

`pyecharts.template.echarts_container(chart)`

Render the html node of container,output `<div></div>` element.

Example

```
# Python Code
bar = Bar('Demo Bar')
# Jinjia2 Context Function
{{ echarts_container(bar) }}
# Html Output
<div id="d09aa82b55384f84a33055f9878c3679" style="width:800px;height:400px;"></div>
```



**echarts_js_content**

`pyecharts.template.echarts_container(*chart)`

Render the js initial code fragment without the `<script></script>` .

**echarts_js_content_wrap**

`pyecharts.template.echarts_js_content_wrap(*args)`

Render the js initial code fragment with the `<script></script>` .

### Example

This is a full example.

The pythonfile:demo.py

```python
from jinja2 import FileSystemLoader
from pyecharts import Bar
from pyecharts.engine import EchartsEnvironment
from pyecharts.utils import write_utf8_html_file

attr = ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"]
v1 = [5, 20, 36, 10, 75, 90]
v2 = [10, 25, 8, 60, 20, 80]
bar = Bar("柱状图数据堆叠示例", jshost=' https://cdn.bootcss.com/echarts/3.6.2')
bar.add("商家A", attr, v1, is_stack=True)
bar.add("商家B", attr, v2, is_stack=True)
env = EchartsEnvironment(loader=FileSystemLoader('.'))
tpl = env.get_template('demo.html')
html = tpl.render(bar=bar)
write_utf8_html_file('demo_gen.html', html)
```

The template file:demo.html

```html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>自定义模板</title>
{{ echarts_js_dependencies(bar) }}
</head>
<body>
{{ echarts_container(bar) }}
{{ echarts_js_content(bar) }}
</body>
</html>
```

0 comments on commit 7620e27

Please sign in to comment.