需要帮助让事情变得干燥 - Rails 3.1
.row
.nine.columns.centered
%ul.bucketlist
- @buckets.each_with_index do |resource, index|
%a{:href => "#{bucket_path(resource)}"}
%li.bucket
%h4= index + 1
%h5= resouce.name
%a{:href => "#{new_bucket_path}"}
%li.bucket.empty
= image_tag "add.gif"
%h5 Add Bucket
我用 3 个不同的视图编写了上面的代码,它们之间只有细微的差别。这对我来说似乎不太干燥,所以我正在寻找一些帮助来清理它。
视图之间只有一些内容有所不同:
@buckets.each
-@buckets
集合需要在@notes
、@ 之间更改单位也是如此。
#{bucket_path}
- 我希望能够传递一个变量,以便bucket_path 成为resource_path。
如果有人可以提供任何帮助,我们将不胜感激。
.row
.nine.columns.centered
%ul.bucketlist
- @buckets.each_with_index do |resource, index|
%a{:href => "#{bucket_path(resource)}"}
%li.bucket
%h4= index + 1
%h5= resouce.name
%a{:href => "#{new_bucket_path}"}
%li.bucket.empty
= image_tag "add.gif"
%h5 Add Bucket
I have the above code written in 3 different views, with only minor differences between them. This doesn't seem very DRY to me, so I'm looking for some help to clean this up.
Between the views only a few things vary:
@buckets.each
- The@buckets
collection needs to change between@notes
,@units
aswell.#{bucket_path}
- I'd like to be able to pass in a variable so that bucket_path becomes resource_path.
If anyone can offer any help, it'd be much appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我对 haml 的经验有限,但我认为您应该能够将通用代码放入部分(例如,名为
_common.html.haml
的文件)中,然后在视图中简单地执行:然后像这样改变部分:
My experience with haml is limited, but I think you should be able to put the common code into a partial (a file named
_common.html.haml
, for instance), and then in the view simply do:Then change the partial like this:
一种解决方案是编写一个辅助函数来生成 html。
人们通常不喜欢助手中的 html,但在这种情况下
将是一个好主意。编写一个传入资源的函数
name ,它会为您生成此代码
另一种方法是检查您所在的控制器并根据该控制器生成所需的代码。例如
<块引用>
resource = @buckets if params[controller]=='bucket'
删除 if 语句的更简洁的方法如下所示,但我还没有尝试过。
<块引用>
exec“资源=@#{params[:controller]}s”
另一种
如果您需要更多帮助,请告诉我。
One solution could be writing a helper function to generate the html.
People typically don't like html in helpers, but in this case it
would be a good idea. Write a function where you pass in the resource
name and it generates this code for you
Another way is to check the controller you are in and generate the required code based on that. For instance
A more condensed way to remove if statements would be something like following, but i havnt tried it out.
Let me know if you need more help.