Ruby on Rails:有条件地显示部分内容
我不确定我在这里是否采用了最好的方法,但我有一个数据块,我想在搜索完成后显示这些数据,并且之前根本不存在。首先,没有什么可显示的,其次它引用的模型为零,因此它抛出异常。
我将此块放置在部分模板中,并将其添加到布局中的适当位置。有没有办法有条件地干净地渲染部分?有没有更好的方法来解决这个问题?
I'm not sure if I'm doing the best approach here, but I have a block of data that I want to show after a search is done and to not be there at all before. First of all, there is nothing to show, and second the model it references is nil so it throws an exception.
I placed this block in a partial template and added it the appropriate spot in my layout. Is there a way to cleanly render the partial conditionally? Is there a better way to approach this problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Ruby 允许您做这样的好事:
为了使其更容易阅读和理解,可以将其写为:
render
是一个函数,您向它传递一个散列,告诉它哪个部分渲染。 Ruby 允许您将内容放在一行中(这通常使它们更具可读性和简洁性,尤其是在视图中),因此if @conditions
部分只是一个常规的 if 语句。也可以这样完成:编辑:
Ruby 还允许您使用
unless
关键字代替if
。这使得代码更具可读性,并且使您不必进行负面比较。Ruby allows you to do nice things like this:
To make this a bit easier to read and understand, it can be written as:
render
is a function, and you pass it a hash that tells it which partial to render. Ruby allows you to put things on one line (which often makes them more readable and concise, especially in views), so theif @conditions
section is just a regular if statement. It can also be done like:Edit:
Ruby also allows you to use the
unless
keyword in place ofif
. This makes code even more readable, and stops you from having to do negative comparisons.一种简单的方法是使用辅助方法。助手往往比直接将逻辑放入视图中更简洁。
因此,您的视图可能类似于:
并且您的助手将有一种方法来控制它:
显然,事物的命名更合适
One easy way is to use a helper method. Helpers tend to be a bit cleaner than putting logic directly in the view.
So, your view might be something like :
and your helper would have a method to control this:
where obviously things are named more appropriately
假设我没听错,您可以在视图级别执行此操作。
希望有帮助。如果没有,也许可以发布您的代码示例。
Assuming I am following you right, you do this at the view level.
Hope that helps. If not, maybe post an example of your code.