Ruby on rails Rails,如何添加到方法html/js?
例如,我有很多类似的页面。只有一个区别:在每个页面上(它们有不同的控制器),它们有不同的变量,适用于这个html.erb文件的是什么 例如,video post html.erbRuby on rails Rails,如何添加到方法html/js?,ruby-on-rails,ruby,ruby-on-rails-3,Ruby On Rails,Ruby,Ruby On Rails 3,例如,我有很多类似的页面。只有一个区别:在每个页面上(它们有不同的控制器),它们有不同的变量,适用于这个html.erb文件的是什么 例如,video post html.erb <% for post in @posts_for_video> here some html and javascript and also ruby code injection <% end %> 和我的照片页面: <% for post in @post_for_ph
<% for post in @posts_for_video>
here some html
and javascript
and also ruby code injection
<% end %>
和我的照片页面:
<% for post in @post_for_photos >
same html as video
same js as video
and same ruby code as video
<% end %>
所以我的问题是:有没有可能将html+js+ruby_代码放到,例如application_controller.rb
或者是否有可能将变量作为参数传递给_some.html.erb
我想,我要找的是(在application_controller.rb中):
把整个代码放进一个部分?供参考: 大概是这样的:
# app/views/shared/_items.html.erb
<% items.each do |item| %>
<!-- html stuff -->
<!-- javascript stuff -->
<%= # ruby stuff %>
<% end %>
#app/views/shared/_items.html.erb
然后,您可以在另一个视图中这样渲染它:
# app/views/examples/show.html.erb
<%= render 'shared/items', items: @items %>
#app/views/examples/show.html.erb
这就是您要找的吗?解决方案是使用表单部分 假设我们有一个页脚。我们不想把这个网站放在我们的网站上,因为它是由我们制作的。我们该怎么办?我们创建名称的一个部分形式 \u footer.html.erb(
表示这是一个局部视图,而不是像show.html.erb
那样的整体视图)
我们可以在里面写字
<div class="container">
<footer class="footer">
<small>
Copyright ©<a href = "https://ca.linkedin.com/in/muntasir-alam-878625114">Muntasir Alam 2016</a>
</small>
<nav>
<nav>
<ul>
<li><%= link_to 'About', welcome_about_path %></li>
</ul>
</nav>
</nav>
</footer>
</div>
注意结构。根据检查当前用户是否正在执行特定操作,或者用户是否实际登录,我有一些代码将由其他一些控制器使用
有关参考信息,请参见
为什么要将其放入
应用程序\u controller.rb
?在我看来,明智的做法是将诸如处理登录检测的方法,以及查找特定用户对应于其中特定内容的方法放在其中。也就是说,您应该保持它的整洁,并且只保留其他控制器将使用的功能。@Muntasir Alam,about application.rb这就是示例。但我要说的是,不要在每个html.erb中重复代码(这个htmls中唯一的区别是一个变量)。或者mb有可能将变量作为参数传递给html.erb?让我直说吧。你想一直在页面上显示一些东西吗?如果是这样的话,我会发布一个解决方案。在试图解决它的时候打断我的头。非常感谢。
# app/views/shared/_items.html.erb
<% items.each do |item| %>
<!-- html stuff -->
<!-- javascript stuff -->
<%= # ruby stuff %>
<% end %>
# app/views/examples/show.html.erb
<%= render 'shared/items', items: @items %>
<div class="container">
<footer class="footer">
<small>
Copyright ©<a href = "https://ca.linkedin.com/in/muntasir-alam-878625114">Muntasir Alam 2016</a>
</small>
<nav>
<nav>
<ul>
<li><%= link_to 'About', welcome_about_path %></li>
</ul>
</nav>
</nav>
</footer>
</div>
helper_method :current_user, :logged_in?
def current_user
@current_user ||= User.find(session[:user_id]) if session[:user_id]
end
def logged_in?
current_user
end
def require_user
unless logged_in?
flash[:danger] = "You must be logged in to perform that action!"
redirect_to root_path
end
end