Posting this answer to help those trying to accomplish the same thing. I was told the code above had security vulnerabilities (which has since been removed see comments below). On the Drupal Slack channel, someone pointed out the following concern with runwithscissors' answer:
"This code is potentially dangerous:$variables['title'] = \Drupal\Core\Render\Markup::create($new_title);
A user could set <script>alert("foo")</script>
as the Node or Term title and potentially execute code on the site. Typically you don’t want to ever create Markup objects manually. For what you’re doing, I’d suggest setting $term_name
to a new key in $variables
, then forming your combined title in the Twig template like {{ term_name}} {{ title }}
"
So what i ended up doing was adding this template_preprocess_page_title
to my MY_SITE.theme file.
(Note: field_manufacturer
is the specific field for my use case, so you would need to change all instances of that to your taxonomy reference field name.)
/* Add field_manufacturer to all node titles with field_manufacturer and not empty */
function template_preprocess_page_title(&$variables) {
$node = \Drupal::request()->attributes->get('node');
if ($node && $node->hasField('field_manufacturer') && !$node->field_manufacturer->isEmpty()) {
$term = \Drupal\taxonomy\Entity\Term::load($node->get('field_manufacturer')->target_id);
$term_name = $term->getName();
$variables['term_name'] = $term->getName();
}
}
This applies to all nodes with the field_manufacturer
, but also checks that the term field is NOT empty with && !$node->field_manufacturer->isEmpty())
. This was critical as the reference field was not required, so nodes that had the field but didn't have a value crashed the site with Error: Call to a member function getName() on null in template_preprocess_page_title()
Then I copied and overwrote the page-title.html.twig
file from my bootstrap base theme which originally renders the title like this:
{% if title %}
<h1{{ title_attributes.addClass('page-header') }}>{{ title }}</h1>
{% endif %}
And changed the H1 title line to this:
{% if title %}
<h1{{ title_attributes.addClass('page-header') }}>
{% if term_name %}
<span class="MY-DESIRED-CLASS-NAME">{{ term_name }}</span>
{% endif %}
{{ title }}</h1>
{% endif %}
This adds a MY-DESIRED-CLASS-NAME
span class to the term_name
. Also by putting it within {% if term_name %}
/{% endif %}
statement, it prevents that class from being rendered in the html where there is no term_name
present.
Hope this helps someone!
template_preprocess_page_title(&$variables)
and change$variables['title']
. The template file for theming the page title ispage-title.html.twig
. To change the title field in a view like theteaser
, I think you would implementtemplate_preprocess_node(&$variables)
, and change$variables['label']
. In this case, the template file would benode.html.twig
.