What is a partial?

Free preview 2 min to read

The same card, rendered over and over

The roadmap page, app/views/catalog/courses/index.html.erb, renders the same course card for every course: image, title, progress bar and badge, with only the data changing. Writing that markup by hand per course would duplicate twenty-plus lines everywhere a course appears. This project writes it once and reuses it:

<%= render partial: "course_card", collection: group.courses, as: :course,
      cached: ->(course) { card_cache_key(course, @progress) },
      locals: { lvl: lvl, level_name: level_name,
                progress: @progress, lesson_counts: @lesson_counts } %>

A partial is a view file meant to be reused

That line renders app/views/catalog/courses/_course_card.html.erb, a .html.erb template like those from the last two courses, written once and called wherever its markup repeats. It runs twice in index.html.erb, once for courses with a category and once for those without. This project has about forty such files, from _navbar.html.erb and _footer.html.erb in the layout to _form_errors.html.erb, _course_card.html.erb, _sponsor_line.html.erb and a dozen admin forms. That kind of reuse is why the mechanism exists.

Where this course goes

  • Lesson 2 covers the underscore naming rule every partial file follows.
  • Lesson 3 covers passing local variables into a partial, like course: and lvl: above.
  • Lesson 4 reads three of this project's partials.
  • Lesson 5 covers rendering a partial that lives in a different folder.
  • Lesson 6 compares the shorthand render form with the explicit one used above.
  • Lesson 7 puts it together and names what comes next.
Lesson 1 of 7 · free

Keep going with lesson 2

The underscore naming convention

Explains the leading underscore in partial filenames and how Rails looks in the calling view's folder.

A free account also gives you the quizzes, your progress and notes, and the discussion.

Type to start searching...