基于json值呈现html的dataset插件
datasette-json-html的Python项目详细描述
数据集json html
用于基于json值呈现html的datasette插件,使用render_cell plugin hook。
此插件查找与非常特定的json格式匹配的单元格值,并在由dataset接口呈现时将其转换为html。
链接
{
"href": "https://simonwillison.net/",
"label": "Simon Willison"
}
将呈现为<a href="">
链接:
<a href="https://simonwillison.net/">Simon Willison</a>
您可以使用"title"
键在链接上设置工具提示:
{
"href": "https://simonwillison.net/",
"label": "Simon Willison",
"title": "My blog"
}
产生:
<a href="https://simonwillison.net/" title="My blog">Simon Willison</a>
链接列表
[
{
"href": "https://simonwillison.net/",
"label": "Simon Willison"
},
{
"href": "https://github.com/simonw/datasette",
"label": "Datasette"
}
]
将呈现为<a href="">
链接的逗号分隔列表:
<a href="https://simonwillison.net/">Simon Willison</a>,
<a href="https://github.com/simonw/datasette">Datasette</a>
href
属性必须以https://
或http://
或/
开头,以避免潜在的xss注入攻击(例如以javascript:
开头的url)。
图像
图像标记更复杂。最基本的版本如下:
{
"img_src": "https://placekitten.com/200/300"
}
这将呈现为:
<img src="https://placekitten.com/200/300">
但也可以包含alt
、caption
、width
和href
中的一个或多个。
如果包含width或alt,它们将作为属性添加:
{
"img_src": "https://placekitten.com/200/300",
"alt": "Kitten",
"width": 200
}
产生:
<img src="https://placekitten.com/200/300"
alt="Kitten" width="200">
href
键将使图像包装在链接中:
{
"img_src": "https://placekitten.com/200/300",
"href": "http://www.example.com"
}
产生:
<a href="http://www.example.com">
<img src="https://placekitten.com/200/300">
</a>
caption
键将所有内容包装成一个奇特的图形/figcaption块:
{
"img_src": "https://placekitten.com/200/300",
"caption": "Kitten caption"
}
产生:
<figure>
<img src="https://placekitten.com/200/300"></a>
<figcaption>Kitten caption</figcaption>
</figure>
预格式化文本
您可以使用{"pre": "text"}
在<pre>
html标记中呈现文本:
{
"pre": "This\nhas\nnewlines"
}
产生:
<pre>This
has
newlines</pre>
如果附加到"pre"
键的值本身是一个json对象,那么该json将被很好地打印出来:
{
"pre": {
"this": {
"object": ["is", "nested"]
}
}
}
产生:
<pre>{
"this": {
"object": [
"is",
"nested"
]
}
}</pre>
将它们与sqlite json函数一起使用
使用这个插件的最强大的方法是与sqlite的JSON functions结合使用。例如:
select json_object(
"href", "https://simonwillison.net/",
"label", "Simon Willison"
);
您可以使用这些函数从表中的数据构造与插件一起工作的json对象:
select id, json_object(
"href", url, "label", text
) from mytable;
json_group_array()
函数是一个类似于group_concat()
的聚合函数,它允许您结合GROUP BY
子句构造json对象列表。
这意味着您可以使用它来构造链接的动态列表,例如:
select
substr(package, 0, 12) as prefix,
json_group_array(
json_object(
"href", url,
"label", package
)
) as package_links
from packages
group by prefix
sql函数urllib_quote_plus()
由于此插件设计用于构造底层json结构的sql,因此可能需要根据sql查询返回的结果构造动态url。
这个插件注册了一个名为urllib_quote_plus()
的自定义sqlite函数来帮助您实现这一点。它允许您在sql查询中使用python的urllib.parse.quote_plus() function。
下面是一个如何使用它的示例:
select id, json_object(
"href",
"/mydatabase/other_table?_search=" || urllib_quote_plus(text),
"label", text
) from mytable;