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

Ruby on Rails中PDF无法在新标签页打开的问题咨询

PDF无法强制在新标签页打开的问题解决思路

问题背景

我在内部应用中遇到PDF无法强制在新标签页打开的问题,调用组件的代码如下:

<%= render "shared/application_form/identity_document_summary",
             application_form: @assessment_section_view_object.application_form,
             changeable: false
             %>

获取文件URL的ERB组件代码中,URL可正常打开文件,但href里的target: :_blank属性不生效:

<%= render(CheckYourAnswersSummary::Component.new(
  id: "identity-document",
  model: application_form,
  title: I18n.t("application_form.tasks.items.identity_document"),
  fields: {
    identification_document: {
      title: "Identity documents",
      href: [:edit, :teacher_interface, :application_form, application_form.identification_document, target: :_blank],
    }, 
  },
  changeable:
)) %>

看到类似问题用了link_to,想知道是否需要重构代码改用link_to替代当前的href?

问题原因

你这里把target: :_blank放在了路由参数数组里,但target是HTML <a>标签的属性,不是路由生成的参数,所以组件无法识别这个属性,自然不会渲染到链接上。

解决步骤

  • 优先检查组件是否支持单独传递HTML属性
    查看CheckYourAnswersSummary::Component的实现代码,看它是否支持在字段配置里直接传入target或html_options这类属性。如果支持,调整代码如下:

    fields: {
      identification_document: {
        title: "Identity documents",
        href: [:edit, :teacher_interface, :application_form, application_form.identification_document],
        target: "_blank" # 单独传递target属性
      }, 
    }
    
  • 如果组件不支持,用link_to生成自定义内容
    如果组件允许字段配置使用content来替代href(即支持渲染自定义HTML),可以直接用link_to生成带target的链接:

    fields: {
      identification_document: {
        title: "Identity documents",
        content: link_to("查看身份文档", [:edit, :teacher_interface, :application_form, application_form.identification_document], target: "_blank")
      }, 
    }
    
  • 最后考虑扩展组件或重构
    如果以上两种方式都不行,才需要考虑修改CheckYourAnswersSummary::Component的代码,让它支持解析并渲染HTML属性;或者完全重构这部分代码,用link_to替代组件的href生成逻辑。

额外注意

部分浏览器可能会对PDF的打开行为有安全限制,但你提到URL能正常打开文件,所以核心问题还是target属性没被正确渲染到链接标签上,按上述步骤处理即可。

内容的提问来源于stack exchange,提问作者David f

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 16:31:03