【问题标题】:Rails 4: Can I pass a partial into a partial?Rails 4:我可以将部分传递给部分吗?
【发布时间】:2016-03-13 16:29:03
【问题描述】:

我发现了很多关于如何将数据、json、字符串等传递到一个部分的信息,但我想将一个部分传递到另一个部分。到目前为止,这是我的代码:

我的 parent.html.erb

      <%= render partial: 'shared/faq_question', locals: { 
        id: '1',
        question: 'A question I\'m asking', 
        answer: 'A string answer that does\'nt cause any problems'
        } %>
    
      <%= render partial: 'shared/faq_question', locals: { 
        id: '2',
        question: 'A question that requires an HTML answer', 
        answer: 'THE PARTIAL SHOULD GO HERE'
        } %>
    
    </ul>
    

    我的_faq_question.html.erb

    <li id="question<%= id %>">
    
      <a href="#question<%= id %>" class="ca" data-activate="#question<%= id %>" data-method2="toggle">
        <i class="close-icon"></i>
        <span><%= question %></span>
      </a>
    
      <div>
        <p><%= answer %></p>
      </div>
    
    </li>
    

    到目前为止,一切都很好。上面的第二个问题的内容中包含 HTML 内容,如下所示:

    <%= render partial: 'shared/faq_question', locals: { 
      id: '22',
      question: 'A question that requires an HTML answer?', 
      answer: "<span>Something</span>
        <ul>
          <li>Some foo</li>
          <li>Some bar</li>
          <li>Content</li>
        </ul>
    
        <span>Keep in mind:</span>
        <ul>
          <li>There is more </li>
          <li>This is great</li>
        </ul>
    
        <span>Please note:</span>
        And another sentence".html_safe
      } %>
    

    我想用部分替换 answer

    我的 _answer.html.erb 部分

    <span>Something</span>
    <ul>
      <li>Some <%= foo %></li>
      <li>Some bar <%= foofoo %></li>
      <li>Content <%= bar %></li>
    </ul>
    
    <span>Keep in mind:</span>
    <ul>
      <li>There is more </li>
      <li>This is great</li>
    </ul>
    
    <span>Please note:</span>
    And another sentence
    

    我尝试添加部分 sn-p 并使用 html_safe 但这会中断并在浏览器呈现存在语法错误时出现错误,这是因为部分答案没有正确转义。

    我的尝试:

    answer: <%= render partial: 'shared/faq_question' %>.html_safe
    

    answer: (<%= render partial: 'shared/faq_question' %>).html_safe
    

    answer: "<%= render partial: 'shared/faq_question' %>".html_safe
    

    我需要做什么才能正确转义部分并让它在浏览器中呈现?

    我还想将数据传入第二部分以替换以下变量:

    <li>Some <%= foo %></li>
    <li>Some bar <%= foofoo %></li>
    <li>Content <%= bar %></li>
    
  • foofoo
  • 酒吧
  • 我们将不胜感激任何正确方向的帮助或想法。 谢谢!

    【问题讨论】:

      标签: ruby-on-rails ruby-on-rails-4 partials


      【解决方案1】:

      你已经在 ruby​​ 块中,不需要额外的 erb-tags,试试

      answer: render(partial: 'shared/faq_question')
      

      【讨论】:

      • 哦,太简单了!你能告诉我,我没有使用 Rails 的经验吗? ;) 非常感谢!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-28
      • 2013-01-16
      相关资源
      最近更新 更多