1

I'm running Drupal 8.2.6, and an Adaptive subtheme and I am trying to modify the page title. I have created the following function in THEME.theme

function THEME_preprocess_page_title(&$variables) {
  $color_title = str_ireplace('some text', 'Some <span class="ct-green">TEXT</span>', $variables['title']);
  $variables['title'] = $color_title;
}

unfortunately, it's not working, at all. I've even tried just

$variables['title'] = 'Hello World';

to see if it would work, but no dice.

EDIT So the hunt goes on!

Apparently AdaptiveTheme doesn't use the page title block, it writes it into node.html.twig via field--node--title.html.twig

so far, I have edited THEME_preprocess_field__node__title(&$variables) with no luck, but THEME_preprocess_node() seems to work. kind of. if i do

$variables['title'] = 'hello world';

it works, but it still won't let me put the span tags in. I have found the reason for that, titles aren't allowed to have code because of XSS threats.

OK. Fine. Fair enough.

There is options in the code to allow you to to allow certain tags (i found documentation, then i lost it ... argghh)

I will keep this question updated as I go

2 Answers 2

3

I think you are looking in wrong place. As far as i remember, in Drupal 8 title is rendered trough block called page_title_block

function MODULE_preprocess_block(&$variables) {
  if ($variables['plugin_id'] == 'page_title_block') {
    $color_title = str_ireplace('some text', 'Some <span class="ct-green">TEXT</span>', $variables['content']['#title']);
    $variables['content']['#title'] = $color_title;
  }
}
2

Not sure it is still relevant after more than 2 years of inactivity, but I just wanted to point out that your approach isn't working most likely because the title is not a string but a Markup object which can't be modified.

You need to create a new one and then assign it to the title variable. Your function should be something like this:

function THEME_preprocess_page_title(&$variables) {
  $color_title = str_ireplace('some text', 'Some <span class="ct-green">TEXT</span>', $variables['title']);
  $variables['title'] = Drupal\Core\Render\Markup::create($color_title);
}

Further reading here.

Your Answer

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

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