2

我正在尝试创建一个简单的部分,它允许我显示代码块而不会在我的代码中经历奇怪的扭曲。

所以我在部分做了这个:

<% lang ||= "" %>
<% language = "lang='#{lang}'" %>

<div class="codebox">
        <% if title %>
            <h3><%= title %></h3>
        <% end %>
    <pre <%= language %>><%=text.unindent%></pre>
</div>

这在 lib 中用于取消缩进字符串(感谢一个非常好的 SO 建议):

class String
    def unindent; gsub(/^#{scan(/^\s+/).min}/, "") end
end

然后,我可以这样做,得到一个非常漂亮的小代码框:

<%= render partial: 'pre', locals: { title: "example.html", lang: 'html', text: "
                <div class='cl' style='text-align:center'>
                  <div class='collapse-group'>
                        <!-- Title, always viewable --> 
                        <a class='bundle' href='#'>'Click here to expand'</a> 
                    <div class='collapse'>
                        <!-- The content to be hidden or shown -->
                    </div> 
                  </div>
                </div>
                "} %>

这变成了这样:

在此处输入图像描述

就像一个魅力,除非我放入一堆 erb,在这种情况下它会发疯并开始到处出错。例如错误产生者(内容不是超级相关。我确保其中的所有引号都是双引号,而“字符串”是单引号):

<%= render partial: 'pre', locals: { title: "example.html", lang: 'html', text: '
                <% sub ||= "" %>
                <% term ||= "(expand)" %>
                <% style ||= "" %>

                <div class="cl" style="text-align:center">
                <div class="collapse-group">
                    <<%=tag%> class="squeeze" style=<%="#{style}"%>> 
                        <%=title%> 
                        <% if sub != "" %> 
                            <small><%= sub %></small>
                        <% end %>
                        <a class="bundle" href="#"><%= term %></a> 
                    </<%=tag%>>
                <div class="collapse">
                ' } %>

任何方式我都可以告诉 html 我在这些引号中输入的是 100% 的文字字符?我已经尝试单独转义 ">"s 和 ">"s 和 "%"s 等等,这是一条混乱(且无效)的路径,我希望不要走下去。

EX 我希望上面的样子:

在此处输入图像描述

4

1 回答 1

1

我认为一个很好的方法是使用#capture,例如在帮助器中(未经测试,只是提示要做什么):

def code_block( title = nil, lang = nil, &block )
  output = capture( &block ) # this is the answer to all your problems
  output = output.unindent   # optional, escape it as you want, too
  # rendering a partial is still possible, 
  # but i'd recommend using an absolute path : 
  render partial: 'my_html_bits/code_block', 
         locals:  {title: title, lang: lang, text: output }
end

那么你可以这样做:

<%= code_block( 'example.html', 'html' ) do %>
  <%# whatever code here will be captured %>
  <p>Even plain old html.</p>
<% end %>

作为旁注:

  • 您的#unindent方法或多或少模仿了 #strip_heredoc 上的现有 ActiveSupportString猴子补丁
  • 在这些情况下,使用#content_tag也可以为您省去很多麻烦,即:

    <<%=tag%> class="squeeze" style=<%="#{style}"%>>
    # more code...
    

    可能变成:

    <%= content_tag tag, class: 'squeeze', style: style do %>
    # more code...
    
于 2013-04-02T19:42:00.997 回答