How to merge multiple partial templates into one file?
I'm using Ruby on Rails 3 to create my web app.
I don't want to create a t开发者_开发技巧emplate file for each tiny partial template so I tried to merge them into one file using content_for
method but it doesn't works.
My ERB template files are as follows.
layout/_fragments.html.erb: contains contents of some partial templates
<% content_for :twitter_checkbox do -%>
<% can_post_twitter = current_user && current_user.twitter_oauth %>
<% label_text = can_post_twitter ? "Post to Twitter" : "Set up your Twitter account" %>
<%= label_tag :twitter, label_text %>
<%= check_box_tag :twitter, 0, false, :disabled => !can_post_twitter %>
<%- end %>
<% content_for :other_content_of_partial_template do -%> # content of another partial template
...
layouts/application.html.erb
<!DOCTYPE html>
<html>
...
<body>
<%= yield %>
</body>
</html>
<%= render 'layouts/fragments', :formats => :erb %>
layouts/_form.html.erb
<%= form_for(@entry) do |f| %>
...
<%= content_for :twitter_checkbox %> # it shows nothing
<% end %>
What is wrong with this way? Are there any other better ways to write multiple partial templates into one file?
I suppose you have run the _form
partial before your main layout had the chance to run the _fragments
partial, so when you display the fragments, they are not yet created.
The action is rendered before the layout, not after. Calling the _fragments
from your action instead of from layout should make it clear whether this is the problem. At least, I believe so ;-)
You're missing the =
sign in the second snippet which would tell Rails to display the returned text.
<%= form_for(@entry) do |f| %>
...
<%= content_for :twitter_checkbox %> # Note <%= - it should now show stuff
<% end %>
精彩评论