在 Rails 中,为什么我会使用局部变量?像我5岁一样解释它。我根本不明白为什么有人会使用它们。
5 回答
它们是避免重复自己的便捷方法。
例如,您可能有多个显示菜单的页面。无需在每个视图中重复菜单的标记,您只需将其放入部分中并在每个页面上呈现。
在其他情况下,通过将复杂视图分成几个部分,可以使它们更易于管理。
You normally use partials to reuse code: let's say you have a list of posts and each post has a small preview with image, title and excerpt. In your blog homepage you have a list of posts, when you group posts by year, you show a list of posts, when you search for a term you have to display a list of posts.
Instead of repeating the logic to display a post preview, you can move that logic to a partial and keep referring to that whenever you need it. You can keep your code DRY and write less code. Moreover, if you realize you want to add something new, you can just change the partial instead of going and hunting for the templates which display the post previews all over your application.
Well, for the exact same reason that you want to use methods, which is reusing code. Say you have a status area in your application, that you want to show in different places. You can just put the view code for that status area in a partial and then use that partial on the corresponding pages.
Since partials can also take parameters, they make it very easy to reuse view code. Also, you can make partials dedicated for certain models of your application. This way, you can just call render @model
and the correct partial is picked by naming conventions.
A partial allows you to separate layout code out into a file which will be reused throughout the layout and/or multiple other layouts.
For example, you might have a login form that you want to display on 10 different pages on your site. Rather than writing the form code 10 times, you can write it once in a partial, and in each of the 10 pages, simply include that partial at the appropriate place in the layout. If necessary, you can pass local instance variables to the partial to make them available to it.
That way, if you need to change the form, you only need to change the code in the partial, one time, rather than changing it 10 times across all of your layouts.
Here is the guide on partials: http://guides.rubyonrails.org/layouts_and_rendering.html#using-partials
And more discussion on getting data/variables into partials: Pass a variable into a partial, rails 3?