使用的是python内置模块 string的Template 这个类,使用方法如下:
import string
a = string.Template("This is ${what}")
b = a.substitute({"what": "book"})
print(b) # This is book
主要使用的功能就是上面的这个示例, 简单讲解一下:
扩展知识
import string
a = string.Template("This is ${what}")
c = a.substitute({"why": "book"})
print(c) # 结果是报错: KeyError: 'what'
2. 如果想避免上面的问题,可以使用safe_substitute,结果是未替换成功的变量会原样显示在字符串中
import string
a = string.Template("This is ${what}")
d = a.safe_substitute({"why": "book"})
print(d) # This is ${what}
3. 表示替换变量的符号有2种使用选择
# 表示替换变量的符号可以使用 ${变量}, 也可以使用 $变量
import string
a = string.Template("This is $what")
b = a.substitute({"what": "book"})
print(b) # This is book
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>show colors</title>
</head>
<body>
<div id="total">
<div id="color1">
<h3>${color1}</h3><br>
</div>
<div id="color2">
<h3>${color2}</h3><br>
</div>
<div id="color3">
<h3>${color3}</h3><br>
</div>
<div id="color4">
<h3>${color4}</h3><br>
</div>
</div>
</body>
</html>
<style>
#total{
font-size: 50px;
}
#color1{
color: orange;
}
#color2{
color: lightgreen;
}
#color3{
color: deepskyblue;
}
#color4{
color: mediumpurple;
}
</style>
2.准备python代码, 代码如下
import string
with open("template.html", "r") as f:
content = f.read()
s = string.Template(content)
with open("show.html", "w") as f1:
f1.write(
s.substitute({"color1": "orange", "color2": "lightgreen", "color3": "deepskyblue", "color4": "mediumpurple"}))
3. 运行python代码,会在当前目录下,生成show.html.效果图如下
本demo演示的功能: 将模板中的颜色与其描述配对, 并显示出来, 效果是不是很强大!
<!--# <!DOCTYPE html>-->
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
<title>Vue</title>
</head>
<body>
<div id="app">
<el-progress :text-inside="true" :stroke-width="40" :percentage=30></el-progress>
<el-progress :text-inside="true" :stroke-width="40" :percentage=40 status="success"></el-progress>
<el-progress :text-inside="true" :stroke-width="40" :percentage=20 status="warning"></el-progress>
<el-progress :text-inside="true" :stroke-width="40" :percentage=10 status="exception"></el-progress>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://unpkg.com/element-ui/lib/index.js"></script>
<script>
var newVue=new Vue({
el:"#app",
data:{
}
})
</script>
</body>
</html>
说明: 该Vue中引入了Element-UI组件(百分比内显),同时将每个进度条展示的数据定义为特殊标识的变量, 待外部替换
import string
# 假设经过一系列操作得出的数据为mock_data
mock_data = {"data1": 30, "data2": 40, "data3": 20, "data4": 10}
with open("vue_template.html", "r") as f:
content = f.read()
s = string.Template(content)
with open("vue_show.html", "w") as f1:
f1.write(
s.substitute(mock_data))
以上就是 Python + Vue + Element-UI 的简单示例, 是不是很通俗易懂?