AssetTagHelper :: image_path外部视图

kno*_*opx 7 ruby-on-rails helpers

据说,ActionController::Base.helpers就像代理一样,可以访问视图外的助手.然而,那里定义的许多方法依赖于控制器变量,我无法成功调用:

ActionController::Base.helpers.image_path("my_image.png")
>> TypeError Exception: can't convert nil into String
Run Code Online (Sandbox Code Playgroud)

在源挖我看到的compute_asset_host方法试图访问config.asset_host,但confignil.

如何image_path从外部视图成功拨打电话?

kei*_*ley 12

使用view_context访问这些辅助方法,在视图中可用.

你可以image_path从控制器这样调用.

view_context.image_path "my_image.png"
Run Code Online (Sandbox Code Playgroud)


Jho*_*ung 5

对于Rails 3,请在此处查看更清晰的解决方案如何在Rails 3 Controller中使用image_path


NAD*_*NAD 0

Mason Jones 发布的这个解决方案对我有用。

在您的应用程序控制器中:

def self.tag_helper
  TagHelper.instance
end

class TagHelper
  include Singleton
  include ActionView::Helpers::TagHelper
  include ActionView::Helpers::AssetTagHelper
end
Run Code Online (Sandbox Code Playgroud)

然后你可以做以下事情,或者任何你需要的事情。

active_scaffold :mything do |config|
  config.columns = [:name, :number, :active, :description]
  config.update.link.label = tag_helper.image_tag('document_edit.png', :width => "30")
  config.delete.link.label = tag_helper.image_tag('document_delete.png', :width => "30")
  config.show.link.label = tag_helper.image_tag('document.png', :width => "30")
  list.sorting = {:name => 'ASC'}
end
Run Code Online (Sandbox Code Playgroud)

您正在 ApplicationController 中创建 TagHelper 的 Singelton 实例。无论您需要什么,这都会为您提供帮助。他在帖子中对此进行了解释。

另外,我用它来扩展我的模型(创建一个更灵活的 image_tag 帮助器,如果不存在图像,它会返回默认图像 - 例如 person.small_image 是 person 模型的实例变量,它使用 tag_helper)。为此,我将相同的代码放入扩展 ActiveRecord::Base 的 Monkey Patch 初始值设定项中。然后,我从模型中调用 ActiveRecord::Base.tag_helper 。这有点混乱,但我是 Rails 新手。可能有一种更清洁的方法。

希望有帮助。