簡體   English   中英

將html導入rails方法(在helper.rb中)

[英]Import html to rails method (in helper.rb)

我需要幾段代碼,並遵循DRY方法(不要重復自己)我想逃避使用這件事並重新輸入它5次或更多次。 所以我想定義包含ruby和html的方法,以及html和js中的ruby代碼。 但我的實現存在問題。

我的html.erb看起來像這樣:

<% div_count = 1 %>
<div>
  <% for post in @posts %>
    <div class="post-on-main-page-<%= div_count %>"
         id="js-count-<%= div_count_for_js %>">
      <script>
        $("#js-count-<%= div_count_for_js %>").click(function(){
          window.location.href = "<%= post_url(post) %>";
        });
      </script>
    <%= image_tag(post.picture.url) %>
    <span><h5><%= post.theme %></h5></span>
  </div>
  <% end %>
<% div_count += 1 %>
<% if div_count == 4 %>
  <% div_count = 1 %>
<% end %>
</div>

我想要create方法,我認為在application_helper.rb中將使用這段代碼。 會是什么樣子:

def method_name(parameter)
<% div_count = 1 %>
    <div>
      <% for post in parameter %>
        <div class="post-on-main-page-<%= div_count %>"
             id="js-count-<%= div_count_for_js %>">
          <script>
            $("#js-count-<%= div_count_for_js %>").click(function(){
              window.location.href = "<%= post_url(post) %>";
            });
          </script>
          <%= image_tag(post.picture.url) %>
          <span><h5><%= post.theme %></h5></span>
        </div>
      <% end %>
    <% div_count += 1 %>
    <% if div_count == 4 %>
      <% div_count = 1 %>
    <% end %>
  </div>
end

結果是我想要的html.erb

<%= method_name(@posts)%>

我怎樣才能使這個工作?

您可以將此代碼移動到某些HTML。 當你想使用它時,你只需要調用render方法。

<%= render 'html_file' %>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM