【问题标题】:Erb from database and image_tag来自数据库和 image_tag 的 Erb
【发布时间】:2013-11-14 09:52:10
【问题描述】:

只是偶然发现了一个问题,到现在还无法解决。设置如下:

我有一个从数据库中提取并呈现为 html 的 ERB 模板

Class MyController < ApplicationController

  include AssetTagHelper
  ...
  def Show
    template=Page.find(...)   # <%=image_tag('Test.png')%>
    @html=ERB.new(template).result(binding)
  end
  ...

现在问题是 image_tag 'src' 解析为 '/images/Test.png',而通常它应该解析为 '/assets/Test.png'。所以我查看了AssetTagHelper 的rails 源代码,这导致我找到AssetUrlHelper 和以下调用链:image_path => asset_path => compute_asset_path。并且 compute_asset_path 合法地声明它实际上应该解析为 /images/Test.png...

我在这里缺少什么?我怎样才能使图像标签工作并给我'assets/Test.png'?

提前感谢所有回复!

【问题讨论】:

  • 如果你知道它总是需要解决什么问题,为什么不直接使用它呢?所以与其返回 .erb 然后在渲染之前处理它,为什么不把你需要的 html 存储在数据库中呢?

标签: ruby-on-rails ruby ruby-on-rails-3 asset-pipeline erb


【解决方案1】:

仅作记录 - 调试时发现通常在 sprockets-rails-2.0.1/lib/sprockets/rails/helper.rb 中会覆盖 compute_asset_path

通过将@html=ERB.new(template).result(binding) 从控制器移动到视图解决了这个问题。希望这对某人有帮助))

【讨论】:

    【解决方案2】:

    例如,我展示了如何从数据库为 Mailer 类创建 ERB。对于其他类都一样。

    已完成从数据库创建电子邮件模板的邮件程序:

    class UserMailer < ActionMailer::Base
    
          # included helper
          include ActionView::Helpers::NumberHelper
          include ActionView::Helpers::TextHelper
          # another helpers...
          # included helper
    
          def mailer(from, to, subject, path, name)
            mail( from: from, to: to, subject: subject, template_path: path, template_name: name )
          end
    
          def get_template(template_name)
            @erb = EmailTemplate.where(name: template_name, mailer_name: UserMailer.to_s.underscore).first rescue ''
            @template_content_html = ERB.new(@erb.template_html).result(binding).html_safe rescue ''
            @template_content_text = ERB.new(@erb.template_text).result(binding).html_safe rescue ''
          end
    
          def test(user_id)
            from = 'from@mail.com'
            recipients = 'to@mail.com'
            subject = "test"
            template_path = "user_mailer"
            get_template(__method__) #def
            template_name = "general"
            mailer(from, recipients, subject, template_path, template_name)
          end
    
        end
    

    对于在 Mailer 中包含帮助器,您可以使用如下构造:

    include ActionView::Helpers::NumberHelper
    

    从 rails 3.2.13 完美运行。之前没试过。

    【讨论】:

      猜你喜欢
      • 2013-07-20
      • 1970-01-01
      • 1970-01-01
      • 2017-07-31
      • 1970-01-01
      • 1970-01-01
      • 2013-10-27
      • 2013-02-02
      • 1970-01-01
      相关资源
      最近更新 更多