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

Rails+React博客平台:如何正确解析富文本并拆分文本与图片?

Rails + React 博客平台富文本内容正确展示方案

问题背景

基于Rails后端CMS(使用Action Text/Trix富文本编辑器)+ React前端搭建的博客平台,后端传递的富文本内容包含action-text-attachment自定义标签,前端直接用dangerouslySetInnerHTML渲染时,浏览器无法识别该自定义标签导致展示异常。尝试手动拆分内容或正则提取附件,均无法保留内容原有顺序。

解决方案

1. 后端序列化优化(用Nokogiri解析替换自定义标签)

放弃正则处理HTML,改用Nokogiri解析富文本结构,将action-text-attachment标签替换为内部的标准HTML元素,确保内容顺序和结构完整。

修改Rails序列化器代码:

include FastJsonapi::ObjectSerializer
require 'nokogiri'

attributes :id, :created_at, :title, :summary

attributes :body do |object|
  doc = Nokogiri::HTML(object.content.to_s)
  # 替换所有action-text-attachment标签为内部的figure元素
  doc.css('action-text-attachment').each do |attachment|
    figure = attachment.at_css('figure')
    attachment.replace(figure) if figure
  end
  # 提取trix-content内部的HTML内容
  content = doc.at_css('.trix-content')&.inner_html || ''
  content.strip.html_safe
end

# 其余属性保持原有逻辑
attributes :heroimage do |object|  
  unless object.heroimage.nil?           
    object.heroimage.url&.split("?")&.first
  end
end

attributes :tags do |object|
  object.tags
end
attributes :Author do |object|
  {
      name: object.user.first_name + " " + object.user.last_name,
      id: object.user.id,
      avatar: object.user.member_detail.avatar.url&.split("?")&.first
  }
end

2. 前端渲染与样式适配

前端无需修改渲染逻辑,直接使用处理后的HTML,补充CSS样式确保排版和媒体展示正常:

React渲染代码(保持原有逻辑)

function BlogPage() {
    useEffect(() => {
        async function fetchData() {
            const resp = await api.postApi.getStoryPage(slug);
            dispatch(setStoryDetails({ data: resp?.data?.data?.data, slug }));
        }
        if (!details[slug]) fetchData();
    }, []);

    return (
        <Skeleton borderRadius={6} h="100%" isLoaded={details[slug]} minH="24rem">
            <Box fontFamily="nunito" fontSize="18px" fontWeight="400" className="content" dangerouslySetInnerHTML={{ __html: details[slug]?.attributes?.body }} />
        </Skeleton>
    );
}

补充CSS样式

.content {
  line-height: 1.6;
  max-width: 800px;
  margin: 0 auto;
}
.content figure.attachment {
  margin: 1.5rem 0;
  text-align: center;
}
.content figure.attachment img {
  max-width: 100%;
  height: auto;
  border-radius: 4px;
}
.content .attachment__caption {
  margin-top: 0.5rem;
  font-size: 0.9rem;
  color: #666;
}
.content .attachment-gallery {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 1rem;
  margin: 1.5rem 0;
}

方案优势

  • Nokogiri解析HTML比正则更可靠,能精准识别节点结构,确保内容顺序完全保留;
  • 将自定义标签替换为浏览器可识别的标准元素,避免渲染异常;
  • 保留原富文本的布局结构(如图片画廊),配合CSS实现与编辑器一致的展示效果。

内容的提问来源于stack exchange,提问作者Moin Ahmed

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 13:35:01