嵌套的 content_tag 在简单的帮助器中抛出未定义的方法 `output_buffer=` [英] Nested content_tag throws undefined method `output_buffer=` in simple helper
问题描述
我正在尝试创建一个简单的视图助手,但是一旦我尝试嵌套几个内容标签,它就会抛出
I'm trying to create a simple view helper but as soon as I try nest a couple of content tags it will throw
NoMethodError: undefined method `output_buffer=' for
def table_for(list, &proc)
t = Table.new
proc.call(t)
t.render_column(list)
end
class Table
include ActionView::Helpers::TagHelper
attr_accessor :columns, :block
def initialize
@columns = Array.new
end
def col(name)
@columns << name
end
def render_column(list)
content_tag :table do
list.each do |c|
content_tag :td, c
end
end
end
end
有什么问题的提示吗?我还看到有一个 XmlBuilder 是不是更适合我的目的?
Any hints of what's wrong? I've also seen that there's a XmlBuilder is that one better for my purpose?
推荐答案
在 嵌套的 content_tag 在简单的助手中抛出未定义的方法 `output_buffer=` 我最终得到了以下解决方案,其灵感来自 Formtastic 的 API.
With help from Nested content_tag throws undefined method `output_buffer=` in simple helper I ended up with the following solution inspired by the API for Formtastic.
<%= table_for(@users) do |t| %>
<% t.col :name %>
<% t.col :email %>
<% t.col :test, :value => lambda { |u| u.email }, :th => 'Custom column name' %>
<% t.col :static, :value => 'static value' %>
<% end %>
直接使用 output_buffer 并可能重新发明轮子,代码看起来像
Using the output_buffer directly and probably reinventing the wheel the code looks like
module ApplicationHelper
def table_for(list, &block)
table = Table.new(self)
block.call(table)
table.show(list)
end
class Column
include ActiveSupport::Inflector
attr_accessor :name, :options
def initialize(name, options = {})
@name = name
@options = options
end
def td_value(item)
value = options[:td]
if (value)
if (value.respond_to?('call'))
value.call(item)
else
value
end
else
item[name]
end
end
def th_value
options[:th] ||= humanize(name)
end
end
class Table
include ActionView::Helpers::TagHelper
attr_accessor :template, :columns
def initialize(temp)
@columns = Array.new
@template = temp
end
def col(name, options = {})
columns << Column.new(name, options)
end
def show(list)
template.content_tag(:table) do
template.output_buffer << template.content_tag(:tr) do
columns.collect do |c|
template.output_buffer << content_tag(:th, c.th_value)
end
end
list.collect do |item|
template.output_buffer << template.content_tag(:tr) do
columns.collect do |c|
template.output_buffer << template.content_tag(:td, c.td_value(item))
end
end
end
end
end
end
end
这篇关于嵌套的 content_tag 在简单的帮助器中抛出未定义的方法 `output_buffer=`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!