我正在制作一个样式指南,输出左边显示的右侧代码。
我知道添加%%会使再培训局
我编写了一个助手,它获取块的内容并在两个地方呈现代码,一个地方显示html,另一个地方显示创建html的源ERB。
问题是,我返回HTML,在那里我想要再培训局。
视图代码
<%= display_code do %>
<%= link_to "Button", "/style_guide, class: "btn" %>
<% end %>助手代码
module StyleGuideHelper
def display_code(&block)
content = with_output_buffer(&block)
html = ""
html << content_tag(:div, content, class: "rendered-code")
html << content_tag(:div, escape_erb(content), class: "source-code-preview")
html.html_safe
end
def escape_erb(code)
code = code.gsub("%=", "%%=")
end
end预期结果 Button <%= link_to "Button","/style_guide,class: btn“%>
实际结果按钮
干杯
发布于 2012-09-22 04:29:48
问题是,这个助手运行块(link_to "Button", ...) --它从未看到块中的源代码,只看到它的输出。您可以用escape_erb替换h来捕获生成的h,但这不会弹回生成它的ERB。
在我看来,你的选择是:
ERB.new(string).result(binding)对其进行计算,以呈现结果;b)显示字符串。callers中所看到的精确格式可能会在没有通知的情况下更改。...sorted按复杂性和成功率的近似顺序排列。
发布于 2015-04-14 14:53:16
下面的代码将允许您检索给定块的代码。
class ERBSource
ERB = ::ActionView::Template::Handlers::ERB
def self.for(block)
new(block).source
end
attr_reader :block, :file, :line_number
def initialize(block)
@block = block
@file, @line_number = *block.source_location
end
def source
lines = File.readlines(file)
relevant_lines = lines[(line_number - 1)..-1] || []
extract_first_expression(relevant_lines)
end
private
def extract_first_expression(lines)
code = lines.slice[0,1].join # add the first two lines so it has to iterate less
lines.each do |line|
code << line
return code if correct_syntax?(compile_erb(code))
end
raise SyntaxError, "unexpected $end"
end
def correct_syntax?(code)
stderr = $stderr
$stderr.reopen(IO::NULL)
RubyVM::InstructionSequence.compile(code)
$stderr.reopen(stderr)
true
rescue Exception
$stderr.reopen(stderr)
false
end
def compile_erb(code)
ERB.erb_implementation.new(
code,
:escape => false,
:trim => (ERB.erb_trim_mode == "-")
).src
end
end这就是帮手的样子
module StyleGuideHelper
def render_example(name, &block)
code = ERBSource.for(block)
content_tag(:h2, name) +
content_tag(:div, &block) +
content_tag(:pre, content_tag(:code, code))
end
endhttps://stackoverflow.com/questions/12540572
复制相似问题