You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Bokeh HTMLTemplateFormatter生成URL链接异常求助

解决Bokeh DataTable中HTMLTemplateFormatter生成URL跳转错误的问题

我之前也碰到过这个问题!核心原因是浏览器把你的URL当成相对路径处理了,自动把当前页面的路径拼到前面,导致跳转出错。解决起来很简单,分两种场景处理:

1. 跳转至外部网站(绝对URL)

确保你的URL是完整的绝对路径,必须包含http://或https://协议头。如果只写example.com,浏览器会把它当成当前域名下的相对路径,自然会拼接当前页面的路径。

示例代码

from bokeh.io import show
from bokeh.models import ColumnDataSource, DataTable, TableColumn, HTMLTemplateFormatter

# 数据源:确保urls是带协议头的完整绝对URL
source = ColumnDataSource(data=dict(
    site_names=["Google", "GitHub", "Bokeh Docs"],
    site_urls=[
        "https://www.google.com",
        "https://github.com",
        "https://docs.bokeh.org/en/latest/"
    ]
))

# 定义HTML模板,target="_blank"可以让链接在新窗口打开
link_template = """<a href="<%= value %>" target="_blank"><%= value %></a>"""
url_formatter = HTMLTemplateFormatter(template=link_template)

# 配置表格列
columns = [
    TableColumn(field="site_names", title="网站名称"),
    TableColumn(field="site_urls", title="链接", formatter=url_formatter)
]

# 创建并显示表格
data_table = DataTable(source=source, columns=columns, width=600, height=300)
show(data_table)

2. 跳转至本地文件

如果是打开本地文件,需要使用file://协议头,注意路径格式:

  • Windows系统:file:///C:/Users/xxx/Desktop/test.html(三个斜杠,盘符前加斜杠)
  • macOS/Linux系统:file:///home/xxx/Desktop/test.html

示例代码片段

source = ColumnDataSource(data=dict(
    file_names=["本地测试文件"],
    file_urls=["file:///C:/Users/xxx/Desktop/test.html"]
))

关键注意点

  • 绝对不能省略协议头(http:///https:///file://),这是浏览器区分相对/绝对路径的核心标识。
  • 如果你的数据源里的URL是不带协议头的,可以在模板里统一拼接,比如:
    # 假设数据源里的url是"www.example.com",模板里拼接https://
    template = """<a href="https://<%= value %>" target="_blank"><%= value %></a>"""
    

内容的提问来源于stack exchange,提问作者jim jarnac

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:30:21