17

如何在Hugo静态博客中嵌入echarts图表

 3 years ago
source link: https://zeqiang.fun/post/techstack/echarts/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

数据可视化嵌入实验

为啥想做这个

想在hugo博客里写一些数据可视化的作品,感觉echarts的可交互性最好,故在网上搜索嵌入方法。看到最好的解决方案是前端大神Alili的一篇博文


具体实现方法

Hugo静态页面支持一种叫做Shortcodes的特性(or功能),是一个可以传参的小模板


1.创建shortcodes模板文件

在目录 ./themes/even/layouts/shortcodes下创建文件echarts.html,如果没有shortcodes文件夹就自己创建一个。紧接着在echarts.html文件中输入以下代码(具体功能可以自定义)

    <div id="echarts{{ .Get `height` }}" style="width: 100%;height: {{.Get `height`}}px;margin: 0 auto"></div>
    <script src="https://cdn.bootcss.com/echarts/3.8.0/echarts.common.min.js"></script>
    <script type="text/javascript">
        // 基于准备好的dom,初始化echarts实例
        var myChart = echarts.init(document.getElementById('echarts{{ .Get `height` }}'));
        // 指定图表的配置项和数据
        var option = JSON.parse({{ .Inner }})
        // 使用刚指定的配置项和数据显示图表。
        myChart.setOption(option);
    </script>

2.在博客文章中的具体使用

在文章中任意位置插入如下代码,这里以echarts官方教程为例子。这里要注意字符型要加上双引号”“,如 “title”,而数值型不用。 特别注意:这里echarts标签<…>复制的时候与花括号{ }前后的空格要去掉

    {{ <echarts height="500"> }}
        {"title":{"text":"ECharts 入门示例"},"tooltip":{},"legend":{"data":["销量"]},"xAxis":{"data":["衬衫","羊毛衫","雪纺衫","裤子","高跟鞋","袜子"]},"yAxis":{},"series":[{"name":"销量","type":"bar","data": [5, 20, 36, 10, 10, 20]}]}
    {{ </echarts> }}


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK