In Drupal 7, there was drupal_get_title()
and drupal_set_title()
. They're history.
I want to alter the page title "Create X" to "Add X" for all X, and I think hook_preprocess_page_title()
in my .theme-file is the right place to do it. (If you disagree, please say so.)
I.e. I want it to be 'Add X' for any 'X' when it originally was 'Create X'. For example: 'Create article' should become 'Add article'. And if the title is 'Bar Article', I should be left as is.
Basically, I want to sniff the title string and if it starts with 'Create ', alter it to 'Add '. This is so far I've gotten, and this is obviously incomplete:
/**
* Implements hook_preprocess_page_title().
*/
First attempt:
function guidedtheme_preprocess_page_titlemytheme_preprocess_page_title(&$variables) {
$request = \Drupal::request();
$route_match = \Drupal::routeMatch();
$title = \Drupal::service('title_resolver')->getTitle($request, $route_match->getRouteObject());
}
I know that I can change the title to some translatable stringSecond attempt, based upon suggestion by doing this4k4:
function mytheme_preprocess_page_title(&$variables) {
$title = $variables['title'];
if ($title instanceof TranslatableMarkup) {
$title = $title->getUntranslatedString();
$title = str_replace('Create', 'Add', $title);
$variables['title'] = t('Some$title);
string' }
else {
$variables['title'] = Markup::create(str_replace('Create', 'Add', $title));
}
}
WhenThe titles I inspectwant to change come from Drupal core and they are translatable, so its the $titleinstanceof TranslatableMarkup
branch that gets executed, whichbut I know have learnt isagree with having a "markup object"fallback in case they're not, I can see that the attribute #translatedMarkup:
is "Create @name
"a good idea.
However, doingwhile a good start, this:
$variables['title'] = t('Add @name');
Changes is not a complete solution. It changes the rendered title of the add article form from "Create article" to "Add @name".
I think my questions boils down to the following:
$title
is not a string. The string is somewhere in there, but how do I extract it to see what it starts with?- How do I actually change it in the context of a preprocess hook. I.e. what is equivalent of
drupal_set_title()
in this context?
I've upvoted the answer by 4k4, as it goes much further towards a solution than my first attempt, but it is still not complete.
I don't want to use the String Overrides module for this for several reasons, mostly because this theme should work across translations without requiring extra configuration when deployed.