如何在Jekyll中遍历页面<a>元素并获取内容与href属性?
问题
能否在Jekyll的Liquid过滤器中遍历处理后的页面内容元素,尤其是遍历页面中所有<a>元素并获取其内容与href属性?我希望能在页面中实现如下类似功能的代码:
<ul> {% for link in content.links %} <li>这里可以使用 {{link.contents}} 和 {{link.href}} 做一些处理。</li> {% endfor %} </ul>
是否有原生功能或插件支持该需求?无需兼容Github Pages。
解决方案
Jekyll的原生Liquid过滤器没有直接提供遍历页面中<a>元素的功能,但可以通过自定义Jekyll插件实现该需求。
你可以借助Jekyll的Hooks机制,在站点渲染前解析页面内容中的Markdown链接(包括行内式和引用式),提取链接文本与URL后存入页面自定义数据字段,之后就能在Liquid模板中遍历使用。
你最终修改后的插件代码如下(可捕获引用式链接并排除图片链接):
Jekyll::Hooks.register :site, :pre_render do |site| site.collections.each do |collection, files| if files.docs.any? files.docs.each do |file| links = [] inline_regex = /[^!]\[([^\]]+)\]\(([^)]+)\)/ referenced_regex = /\[([^\]]+)\](?:\[([^\]]+)\])?[^:]/ references_regex = /\[([^\]]+)\]: ?(.+)/ file.content.scan(inline_regex).each do |match| if match.length == 2 links << { "text" => match[1], "ref" => match[1], "link_url" => match[2] } end end file.content.scan(referenced_regex).each do |d_match| if d_match.length == 2 link = { "text" => d_match[0], "ref" => d_match[1] } elsif d_match.label == 1 link = { "text" => d_match[0], "ref" => d_match[0] } end file.content.scan(references_regex).each do |s_match| if s_match[0] == link["ref"] and s_match[1] links << link.merge!({ "url" => s_match[1]}) end end end file.merge_data!({ "links" => links}) end end end end
代码说明
- 注册站点级
pre_render钩子,在页面渲染前执行处理逻辑 - 用正则分别匹配行内式Markdown链接(排除图片链接,因为图片链接以
!开头)和引用式Markdown链接 - 将提取到的链接文本、URL整理为哈希结构存入
links数组 - 通过
merge_data!把links数组添加到页面自定义数据中,之后可在Liquid模板中通过page.links遍历这些链接
内容的提问来源于stack exchange,提问作者regret
相关产品推荐
相关产品推荐

