創建 AnyChart 模板的思路是分離圖表設置和數據部分,然後將模板稍作改變就可以應用於另一個圖表。比如你在站點中會反覆用到一個有相同標題和座標軸的柱狀圖,你就可以將它存爲XML文件,當你需要用到這個圖表的時候,只需調用這個模板就可以了,而不用再從一個地方將圖表的配置複製粘貼到另一個地方。本文就爲你講解如何創建 AnyChart 模板,如何存儲模板以及如何應用模板。
如何創建模板
首先確定你要創建一個什麼樣的圖表,然後確定你想要哪些設置,最後就開始着手創建吧。
這裏有一個條形圖的示例:
<?xml version="1.0" encoding="UTF-8"?> <anychart> <charts> <chart plot_type="CategorizedHorizontal"> <data> <series name="Year 2003" type="Bar"> <point name="Department Stores" y="637166" /> <point name="Discount Stores" y="721630" /> <point name="Men's/Women's Specialty Stores" y="148662" /> <point name="Juvenile Specialty Stores" y="78662" /> <point name="All other outlets" y="90000" /> </series> </data> <chart_settings> <title enabled="false" /> <axes> <y_axis> <title> <text>Sales</text> </title> </y_axis> <x_axis> <labels align="Outside" /> <title> <text>Retail Channel</text> </title> </x_axis> </axes> </chart_settings> </chart> </charts> </anychart>
然後將它移動到模板內,示例代碼如下:
<chart plot_type="CategorizedHorizontal"> <chart_settings> <!-- No title --> <title enabled="false" /> <axes> <!-- X Axis Settings --> <y_axis> <title> <text>Sales</text> </title> </y_axis> <!-- X Axis Settings --> <x_axis> <labels align="Outside" /> <title> <text>Retail Channel</text> </title> </x_axis> </axes> </chart_settings> </chart>
將模板命名爲"Bar Chart With No Title #1",所以在上面代碼的首行添加這行代碼:
<template name="Bar Chart With No Title #1">
接下來就是如何存儲模板的問題。
如何存儲模板
內部模板
你可以將模板存儲在圖表XML內,在<anychart>節點的<templates>子節點內:
<?xml version="1.0" encoding="UTF-8"?> <anychart> <templates> <template name="No Title #1"> <chart plot_type="CategorizedHorizontal"> <chart_settings> <title enabled="false" /> </chart_settings> </chart> </template> </templates> <charts> <!-- Charts definition goes here --> </charts> </anychart>
那麼這樣的模板就是內部模板,點擊查看條形圖效果:
外部模板
你也可以創建一個模板文件,然後將它和某個圖表XML關聯,模板文件根節點將是<templates>:
<templates> <template name="No Title #1"> <chart plot_type="CategorizedHorizontal"> <chart_settings> <title enabled="false" /> </chart_settings> </chart> </template> </templates>
如何應用模板
把模板應用於圖表,只需在<chart>節點的template屬性中設置名稱:
<?xml version="1.0" encoding="UTF-8"?> <anychart> <charts> <chart template="Bar Chart With No Title #1"> <data> <series name="Year 2003" type="Bar"> <point name="Department Stores" y="637166" /> <point name="Discount Stores" y="721630" /> <point name="Men's/Women's Specialty Stores" y="148662" /> <point name="Juvenile Specialty Stores" y="78662" /> <point name="All other outlets" y="90000" /> </series> </data> </chart> </charts> </anychart>
內部模板:如果模板指定在XML文件的<templates>節點內,只需知道一個名稱就可以了:
<template name="No Title #1">
外部模板:如果模板指定在一個外部XML文件內,那就要在path屬性下的<templates>節點內設置它的名稱:
<templates path="templates.xml" /> <chart template="No Title #1">