2

Using Drupal 7 and creating a number of books with the Books module. They each have their own specific design, so specific CSS needed per book. I know I could create specific content types for each book but I think that would become unmanageable as the number of books grow. We are using the Code Per Node module, we could make use of the Context module to detect which book it is, and then insert a block somewhere on the page with some associated CSS. In theory that would work but is there a better way to do this?

1

In Drupal 7, you can add a CSS class to the <body> tag for your book. For nodes, you have the class added by default. For example page-node-2056, for the /node/2056 path.

For Book nodes, you might add the book ID inside your template.php theme file, in the theme_preprocess_html function:

function MYTHEME_preprocess_html(&$vars) {
  // If on an individual node page, add the book ID to body classes.
  if ($node = menu_get_object()) {
    if (isset($node->book['bid'])) {
      $vars['classes_array'][] = drupal_html_class('book-id-' . $node->book['bid']);
    }
  }
}

You can then take the ID for each book and add all the style definitions in a single CSS file. Something like the following:

.book-id-xxx {
  /* Style for book xxx. */
}
.book-id-yyy {
  /* Syle for book yyy. */
}
... and so on

Would it make sense for what you need?

  • Maybe I misunderstood but I don't think it adds the ID for the book but for the node — so if you had a book with 500 pages, you'd need 500 selectors (per rule). It would be very hard to maintain… – pingin Mar 16 '16 at 10:28
  • 1
    @pingin, you are completely right! I assumed the book ID was added too. I have just updated my answer explaining how you can add the book ID to the body classes. I hope it can be useful. – dinopmi Mar 16 '16 at 11:09
  • 1
    I would just add another class 'book' as well so as to target CSS used for all books. – J. Reynolds Mar 16 '16 at 11:26
  • @dinopmi — brilliant, that's exactly what I need! Solves my problem perfectly. Many thanks. – pingin Mar 16 '16 at 12:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.