1

I use the Drupal 8 Book module for books where each chapter has a different author.

The Book Navigation block uses book-tree.html.twig (core/modules/book/templates) to generate a book tree showing chapter titles. I want to show author names also.

I can subclass and edit book-tree.html.twig, but I don't know how to get the author name passed in so I can use it. How do I go about this? Only the title, the url, and some flags are passed in now.

As an alternative, I can get the id for each chapter node from its url as a string. Can I use this id to load the chapter node from within the twig template? If so, I can get the author name from the node directly.

2

Drupal offers preprocess functions where additional variables for templates can be set up.

The naming convention is THEMENAME_preprocess_THEMEHOOK(). In your case, you want to add a variable for book-tree.html.twig. The machine name for this is the first part of the template, with underscores replacing hyphens. In this case it would be book_tree. So your function would be THEMENAME_preprocess_book_tree().

Preprocessors receive a single argument, an array. The keys of this array become the variables available in your twig template.

THEMENAME_preprocess_book_tree(&$vars) {
  $vars['book_author'] = some_function_that_gets_the_author();
}

Now the variable book_author will be available to your template.

  • Thanks a lot @Jaypan! I got it working. Took me a while because I simplified the question (I'm actually getting an array of entity references to authors from each chapter). – Marshall Morrise Nov 21 '18 at 16:34
0

Just in case it may benefit others, here's the code from my .theme file based on the helpful suggestion from @Jaypan. It's different from what he suggested because instead of passing a single variable to a node twig template (as I explained in my simplified question), I'm actually passing an array of entity references (the authors of each book chapter) to the book tree template, which accepts an array of items, each item representing a book chapter.

function my_theme_preprocess_book_tree(&$vars)
{
    foreach ($vars['items'] as $id => &$chapter) {

        $node = \Drupal\node\Entity\Node::load($id);
        $authors = $node->get('field_authors');

        if (count($authors) > 0) {

            $chapter['authors'] = $authors;
    }
}

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.