![](/img/trans.png)
[英]Ruby on Rails Helper Method - HTML is displayed as plain text
[英]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.