Middleman ships with a set of view helpers available in every template. One of the most practical is page_classes, which turns the path of the page being rendered into a string of CSS class names. Put it on the body tag of your layout and every page gets a predictable hook for page-specific styles, without adding classes by hand.
Using it in a layout
<!-- source/layouts/layout.erb -->
<!doctype html>
<html>
<head>
<title><%= current_page.data.title %></title>
</head>
<body class="<%= page_classes %>">
<%= yield %>
</body>
</html>The classes are built from the segments of the path. A page at the site root gets a class based on its own name, while a nested page gets a class for each level, joined with underscores, so a page inside a folder can be styled both as part of that section and individually.
Styling with the generated classes
/* Applies to every page in the projects section */
body.projects .sidebar { display: none; }
/* Applies to one specific page */
body.projects_archive .listing { columns: 2; }Why it is useful
- No per-page frontmatter: you do not need to remember to add a
body_classkey to every page. - Section styling: because each folder level contributes a class, you can target a whole section with a single selector.
- JavaScript hooks: scripts can check
document.body.classListto decide whether to run page-specific behaviour.
Tips and pitfalls
Because the classes come from the path, renaming or moving a page changes its classes and can quietly break styles. If a page's styling is important and the URL may change, add a stable class of your own alongside the generated ones:
<body class="<%= [page_classes, current_page.data.body_class].compact.join(' ') %>">It is also worth writing a quick test for the helper's output on a few representative paths when you rely on it heavily. A feature such as "Given a page at projects/archive.html, when I build the site, then its body should have the class projects_archive" documents the convention for new team members and protects the stylesheets from accidental changes in how pages are organised.
Finally, keep the generated classes for styling and light scripting. Business logic that depends on which page is being shown belongs in data or frontmatter, where it is explicit.