问题描述
我有这个帮手:
def markdown(text)
commonmarker.render_html(text.to_s,:HARDBREAKS,[:autolink]).html_safe
end
但我希望像 +33 7 87 12 10 21
这样的电话号码呈现 tel:
链接。
我弄明白了正则表达式:
PHONE_NUMBER_REGEXP = /\+?[ 0-9()-]+[0-9)]/
但我找不到如何与 commonmarker https://github.com/gjtorikian/commonmarker
集成好像我需要创建一个自定义渲染器 https://github.com/gjtorikian/commonmarker#creating-a-custom-renderer
我也试过:
text.gsub(PHONE_NUMBER_REGEXP) { |match| "[#{match}](tel:#{match})" }
没有成功
解决方法
放弃尝试扩展 CommonMarker 并仅对 html 输出进行 gsub-ed,由于转义,运行良好且安全:
module ApplicationHelper
PHONE_NUMBER_REGEXP = /\+?[ 0-9()-]{9,}[0-9)]/
def markdown(text)
html = CommonMarker.render_html(text.to_s,:HARDBREAKS,[:autolink]).html_safe
html.gsub(PHONE_NUMBER_REGEXP) do |match|
"<a href=\"tel:#{h(match)}\">#{h(match)}</a>"
end.html_safe
end