Bootstrap Rails,将分页添加到内容索引中



Rails自动生成了这个列表。它列出了我的数据库的内容,我想引导它,添加分页和一些漂亮的CSS。

<p id="notice"><%= notice %></p>
<h1>Listing Posts</h1>
<table>
  <thead>
    <tr>
      <th>Name</th>
      <th>Title</th>
      <th>Content</th>
      <th colspan="3"></th>
    </tr>
  </thead>
  <tbody>
    <% @posts.each do |post| %>
      <tr>
        <td><%= post.name %></td>
        <td><%= post.title %></td>
        <td><%= post.content %></td>
        <td><%= link_to 'Show', post %></td>
        <td><%= link_to 'Edit', edit_post_path(post) %></td>
        <td><%= link_to 'Destroy', post, method: :delete, data: { confirm: 'Are you sure?' } %></td>
      </tr>
    <% end %>
  </tbody>
</table>
<br>
<%= link_to 'New Post', new_post_path %>

此表单出现在生成的控制器的index.html.erb中。

在这种生成的文件上添加CSS的最快方法是什么?我已经在相应的.scs文件中导入了Bootstrap,但真的有必要在各处手动定义引导程序类吗?

我不能用一些漂亮的宝石来欺骗吗?

一个不错的例子是kaminari宝石。安装它,

在你的控制器中,你可以做这样的事情,

@posts = Post.page(params[:page]).per(10)

其中page()接受要dispally的第n个数字页面,而per()表示一个页面中要显示的帖子数量。在您的观点中,简单地放置

<%= render @posts %><!-- You can wrap it with a table and bootstrap classes -->
<%= paginate @posts %><!-- At the end of the page. This will take care of pagination -->

对于渲染帖子,kaminari将默认在views/posts/中查找部分_post.html.erb

  <tr>
    <td><%= post.name %></td>
    <td><%= post.title %></td>
    <td><%= post.content %></td>
    <td><%= link_to 'Show', post %></td>
    <td><%= link_to 'Edit', edit_post_path(post) %></td>
    <td><%= link_to 'Destroy', post, method: :delete, data: { confirm: 'Are you sure?' } %></td>
  </tr>

这将有你的内容为一个帖子。请记住,在分部中,您指的是像post这样的单个post对象,而不是@post

使用table类,如:

<table class="table"> 

并使用will_paginate bootstrap进行分页。这是链接https://github.com/bootstrap-ruby/will_paginate-bootstrap.

据我所知,没有任何gem可以为模板注入样式。

最简单的解决方案是自己添加引导程序样式。如果你想要应用程序范围内相同的基本结构,并且你计划使用生成器,你可以自定义适当的模板。

您可以将自定义模板放置在lib/templates/TEMPLATE_ENGINE/GENERATOR_NAME/VIEW_NAME.html.ext

例如,要覆盖rails脚手架生成器的haml视图,可以创建以下文件:

lib
├── tasks
└── templates
    ├── haml
    │   └── scaffold
    │       ├── _form.html.haml
    │       ├── edit.html.haml
    │       ├── index.html.haml
    │       ├── new.html.haml
    │       └── show.html.haml

有关自定义生成器的更多信息,请参阅指南。

您只需要替换要自定义的视图的模板。

有一种方法可以加快rails应用程序的启动:自定义表单生成器。这将允许您以熟悉的方式编写表单,并为您添加引导程序样板。simple_form是一个很好的资源。

如果您已经创建/生成了多个视图,那么手动添加样式可能会更容易。

就分页而言,kaminari似乎是这些天的热门,你可以很容易地自定义视图(或者可能使用gem来自定义它们)。

请记住,自定义生成器模板、配置simple_form和配置分页可能会比自己手动添加样式做更多的工作。然而,这可能会带来长期回报(尤其是当你刚刚开始一个大型项目时)。

最新更新