I'm trying to create a preprocess function to add one of my fields to be displayed alongside the title of my specific content type. So, instead of my title just saying Book Name, it'll say Book Name - 2018. Basically, the year would come from a field in the content type called field_year.

I have the following in my .theme file which doesn't seem to work but I really don't know where to go from here as I've not dabbled with preprocesses too much:

function THEME_preprocess_node__books(&$variables) {
  $node = $variables['node'];
  $variables['fields']['title'] = ($node->getTitle() + $variables['content']['field_year']['0']['#context']['value']);

Let me know what I'm doing wrong and what's the best way to go about this.

  • 1
    You should attempt to grab the field value directly not from the render array, and of course ensure it has value before concatenating
    – Kevin
    Commented Jul 18, 2018 at 20:53

1 Answer 1


Your question may lead to different opinion-based answers. Some might say: Display Suite. Others might say: do it in templates. And you could also: hide this certain field to then preprocess it back as suffix of the title (hook_preprocess_page_title).

All of them are no ideal solutions, IMHO. Display Suite is too heavy. Templates get too fiddly too fast (and I don't like how they can make the Field UI needless). Same for the preprocess function. Although if I would be forced to choose one of the named options I'd rather take the preprocess approach.

What I'd recommend instead is to solve your problem the other way around: Make the title a field, a pseudo field to be precise, that can be placed like any other field in the "Manage display" settings of any content type. Then you simply can drag this title field next to your other field and style them with some basic CSS to be displayed inline.

If you are interested in making the title a pseudo field to solve your problem just implement the code snippets I documented in my other answer on that topic: https://drupal.stackexchange.com/a/263740/15055

Still, if doing it that way you need to edit node.html.twig to remove the default (hard-coded) title output from it, to prevent getting printed twice when viewing this node not as page. Your node title now will be printed like any other field. And of course you also may need to prevent the title block from being printed on your node pages. This can be done per content type in the block settings if I remember it right.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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