Как изменить title drupal

In Drupal 7, I could change the page title with drupal_set_title(t('New page title')). When I try it in Drupal 8, I get a There is no such function error. How can I change the page title?

In Drupal 7, I could change the page title with drupal_set_title(t('New page title')). When I try it in Drupal 8, I get a There is no such function error.

How can I change the page title?

apaderno's user avatar

apaderno

95.5k15 gold badges158 silver badges283 bronze badges

asked Nov 24, 2015 at 5:22

Jeff Madison's user avatar

As reported in drupal_set_title() and drupal_get_title() were removed that function is deprecated in Drupal 8.

For a dynamic title set from a controller, the code the change record suggests is the following one.

mymodule.test:
  path: '/mymodule/test'
  defaults:
    _controller: 'DrupalmymoduleControllerTest::getContent'
    _title_callback: 'DrupalmymoduleControllerTest::getTitle'

The controller code is the following one.

class Test {

  /**
   * Returns a page title.
   */
  public function getTitle() {
    return  'Foo: ' . Drupal::config()->get('system.site')->get('name');
  }

  /**
   * Returns a page render array.
   */
  public function getContent() {
    $build = array();
    $build['#markup'] = 'Hello Drupal';
    return $build;
  }

}

Alternatively, as the same change record suggests, you could use the #title property in a render array. This should be generally avoided, since the title for the page when fully rendered could be different from the title in other contexts (like in the breadcrumbs).

class Test {

  /**
   * Renders a page with a title.
   *
   * @return array
   *   A render array as expected by drupal_render()
   */
   public function getContentWithTitle() {
     $build = array();
     $build['#markup'] = 'Hello Drupal';
     $build['#title'] = 'Foo: ' . Drupal::config()->get('system.site')->get('name');
     return $build;
   }

}

apaderno's user avatar

apaderno

95.5k15 gold badges158 silver badges283 bronze badges

answered Nov 24, 2015 at 5:31

Yuseferi's user avatar

YuseferiYuseferi

21.4k21 gold badges114 silver badges204 bronze badges

1

drupal_set_title() in Drupal 8

$request = Drupal::request();
if ($route = $request->attributes->get(SymfonyCmfComponentRoutingRouteObjectInterface::ROUTE_OBJECT)) {
  $route->setDefault('_title', 'New Title');
}

drupal_get_title() in Drupal 8

$request = Drupal::request();
if ($route = $request->attributes->get(SymfonyCmfComponentRoutingRouteObjectInterface::ROUTE_OBJECT)) {
  $title = Drupal::service('title_resolver')->getTitle($request, $route);
}

answered Apr 26, 2016 at 22:27

rpayanm's user avatar

rpayanmrpayanm

3,5813 gold badges25 silver badges49 bronze badges

3

Change the title tag in the head of your HTML document.

function mymodule_preprocess_html(&$variables) {

  $variables['head_title']['title'] = $something;
}

Change the title that appears in the page content.

function mymodule_preprocess_block(&$variables) {

  if ('page_title_block' == $variables['plugin_id']) {
    $variables['content']['#title'] = $something;
  }
}

answered Feb 4, 2017 at 18:47

arnoldbird's user avatar

arnoldbirdarnoldbird

9697 silver badges21 bronze badges

That function was removed from Drupal 8.
Change record:
drupal_set_title() and drupal_get_title() were removed.

You could now set the title when defining the routes in modulename.routing.yml.
Example of how it could be done, is shown the change record link above.

answered Nov 24, 2015 at 5:29

AjitS's user avatar

AjitSAjitS

10.9k7 gold badges40 silver badges73 bronze badges

I found in D8 that if you’re wanting to alter the title for an entity view, you can use hook_ENTITY_TYPE_view_alter(). For example, here’s how you could change the view of a user entity with a field on the user «field_display_name», rather than the user ID as the title:

/**
* Implements hook_ENTITY_TYPE_view_alter().
*/
function mymodule_user_view_alter(array &$build, DrupalCoreEntityEntityInterface $entity, DrupalCoreEntityDisplayEntityViewDisplayInterface $display) {
  $build['#title'] = $entity->get('field_display_name')->getString();
}

answered Dec 11, 2017 at 15:58

Tyler Fahey's user avatar

Tyler FaheyTyler Fahey

1,0628 silver badges10 bronze badges

1

I’ve found another way, which may be simpler if you don’t have a controller and want to modify the title throughout your website. You can use it to modify the title based on the current node.

First, remove the tag in your html.html.twig
Then, hook hook_page_attachments_alter

function mytemplate_page_attachments_alter(array &$page) {
    $page['#attached']['html_head'][] = [
        [
          '#tag' => 'title',
          '#value' => "My title"
        ],
        'title'
    ];
}

You can get the current node of taxonomy term with

$node = Drupal::routeMatch()->getParameter('node');
$term = Drupal::routeMatch()->getParameter('taxonomy_term')

answered Jun 6, 2016 at 13:38

Kodiak's user avatar

KodiakKodiak

1436 bronze badges

Getting the page title works fine as written in @rpayanm’s answer. But setting it turned out to be quite complicated. Finally found out that hook_preprocess_HOOK() could simply be used to preprocess the page title quite easily.

/**
 * Implements hook_preprocess_HOOK().
 */
function MYMODULE_preprocess_page_title(&$variables) {

  if ($MYLOGIC === TRUE) {

    $variables['title'] = 'New Title';
  }
}

And as already mentioned in other answers here you might additionally use hook_preprocess_html() to set the HTML head title tag accordingly.

answered Mar 30, 2017 at 9:30

leymannx's user avatar

leymannxleymannx

16.9k6 gold badges63 silver badges116 bronze badges

Take a look at Automatic Entity Label, a very well crafted contributed module for setting node titles and the like.

(Note that ‘page title’ is a more colloquial way of saying ‘entity label’, where ‘page’ is a content entity and ‘label’ encompasses the title and the equivalent for other entities e.g. comment subjects, taxonomy term names.)

While op appears to be asking for guidance on writing custom code, it’s not clear from available details that custom code is the best recommendation. For readers without a very specific reason for duplicating a feature available from contributed code, the Drupal community strongly advises (and site owners strongly benefit from) adopting an existing module.

answered Apr 20, 2017 at 18:53

Kay V's user avatar

Kay VKay V

6101 gold badge4 silver badges16 bronze badges

drupal_set_title() and drupal_get_title() both are removed from drupal 8 but the best part is this there is a separate block for page_title. User can hide or add this block on any page/region.

There are 2 solutions for this.

  1. Disable title_block on particular page and add new custom block with some markup for title. Now place this block just after the title_block in drupal block section.
  2. By using hook_preprocess_block() function in your custom_theme.theme file.
    Here is the code example:

    function custom_themename_preprocess_block(&$variables) {
      if ('page_title_block' == $variables['plugin_id']) {
        $request = Drupal::request();
        $path = $request->getRequestUri(); // get current path
        if(strpos($path, 'user')) { //check current path is user profile page
          $variables['content']['#title'] = 'My Profile';
        }
      }
    }
    

    In my case I have used above 2nd method, which will work only for user profile page.

answered Dec 21, 2017 at 13:06

Manav's user avatar

ManavManav

2191 silver badge9 bronze badges

0

I struggled with this and tried all of the solutions above. The solution that finally worked was:

function mymodule_preprocess_html(&$variables) {
  $variables['head_title']['title'] = $something;
}

but only after I updated my custom module weight:

drush php:eval "module_set_weight('mymodule', 10);"

answered Mar 22, 2018 at 10:52

Peter's user avatar

PeterPeter

514 bronze badges

i have changed the page_title block for user/uid to a different custom account field name like this :

function hook_preprocess_block(&$variables) {  
  $path = Drupal::request()->getpathInfo();
  $arg = explode('/', $path);
  if (isset($arg[2]) && $arg[2] == 'user' && isset($arg[3])) {
    if (isset($variables['elements']['content']['#type']) && $variables['elements']['content']['#type'] == 'page_title') {
      $account = DrupaluserEntityUser::load($arg[3]);
      if(isset($account) && isset($account->field_mycustomfield->value)){
        $variables['content']['#title']['#markup']=$account->field_mycustomfield->value;
      }
    }
  }
}

answered Oct 18, 2019 at 15:00

Matoeil's user avatar

MatoeilMatoeil

3,0312 gold badges26 silver badges51 bronze badges

Здравствуйте, читатели блога FairHeart.ru! Значение Title и мета тегов Description и Keywords для поискового продвижения сайта трудно переоценить. По умолчанию Drupal формирует Title автоматически из основного заголовка материала, возможность задать мета теги Description и Keywords вовсе отсутствует. Такие просчеты с точки зрения SEO недопустимы. Сегодня я расскажу о двух модулях Page Title и Metatags Quick, позволяющих решить данную проблему.

Метра теги Drupal

В этой статье рассмотрена только техническая сторона вопроса. Что же касается правил формирования Description, Keywords и Title Drupal с точки зрения SEO, то этой теме я посвятил отдельную статью. Настоятельно рекомендую с ней ознакомиться.

Настойка Title в Drupal — модуль Page Title

Страница Page Title на drupal.org. Установите модуль в систему и активируйте. К сожалению, модуль плохо русифицирован, большая часть интерфейса на английском языке.

Переходим к настройкам в раздел «Конфигурация» — «Поиск и метаданные» — «Page Titles». Здесь задаются шаблона для разного рода страниц сайта. Я бы посоветовал задать только первые два шаблона:

  • «по умолчанию» — [current-page:page-title]
  • для главной станице (Frontpage) — [site:name] | [site:slogan]

Настройка шаблона title

Заметьте, в шаблоне «по умолчанию» я удалил вторую часть кода, отвечающую за вывод названия сайта. Не знаю как google, но яндекс текст после знака «|» учитывает. Это значит, что название сайта в конце каждого title разбавляет его, делая менее уникальным.

Теперь переходим к настройкам типов материалов. Открываем, к примеру, настройки Статьи. В самом низу появляется новая вкладка Page Title Settings, она то нам и нужна.

Включаем поле title

Ставим галочку в пункте Page Title Field и сохраняем настройки. Повторяем эти действия для всех используемых в Drupal типов материалов.

Теперь при создании материала нам доступно новое поле, отвечающее за формирование Title в Drupal.

title материала

Настройка Keywords и Description в Drupal — модуль Metatags Quick

Установите модуль Metatags Quick в Drupal и активируйте (составляющие Extra functionality и Upgrade from nodewords нам не понадобятся).

Переходим в раздел «Конфигурация» — «Поиск и метаданные» — «Meta tags (quick) settings». Здесь представлен список всех доступных мета тегов.

включаем мета теги

Помимо особенно важных Description и Keywords есть еще и необязательные:

  • Канонический URL — позволяет задать основной адрес страницы. Если на сайте будет несколько страниц с одинаковым контентом, но разными URL адресами, то основной из них будет считаться та, чей адрес указан в мета теге «Канонический URL».
  • Авторские права (Copyright) — даем ссылку на свой сайт, чтобы показать авторство.
  • Robots — позволяет разрешить или запретить индексацию отдельных страниц сайта.

Включаем мета теги для Материалов и Терминов таксономии. Каждый мета тег создаст для себя отдельное поле.

К примеру, заходим в «Структура» — «Типы материалов» — «Статья» — «Управление полями». Там уже созданы новые поля под мета теги. В моем случае это (Meta)Описание и (Meta)Ключевые слова. Можно для удобства отредактировать порядок вывода.

управление полями мета тегов

Далее идем на вкладку «Управление отображением». Значение мета тегов должно быть доступно только поисковым системам, но не обычным пользователям. Скрываем оба поля для полной версии материала и для анонса.

настройка отображения

Тоже самое проделываем для всех типов материалов и терминов таксономии.

В модуле Metatags Quick есть подсистема Extra functionality, отвечающая за автоматическое формирование мета тегов на основе содержания страницы. Я специально не буду ее рассматривать, чтобы у вас не было соблазна ей воспользоваться. Title, Keywords и Description в Drupal обязательно нужно задавать для каждой страницы в ручную! Так что не ленитесь.

Description и Keywords для главной страницы

И все хорошо в модуле Metatags Quick, да только Description и Keywords для главной страницы он не прописывает. Досадный промах, который следует устранить своими силами. Переходим на сервер в каталог с активной темой Drupal и открываем на редактирование файл template.php.

В самый конец вставляем следующий код:

function НАЗВАНИЕТЕМЫ_page_alter($page) {
$meta_description = array(
'#type' => 'html_tag',
'#tag' => 'meta',
'#attributes' => array(
'name' => 'description',
'content' => 'Текст мета тега Description'
)
);
$meta_keywords = array(
'#type' => 'html_tag',
'#tag' => 'meta',
'#attributes' => array(
'name' => 'keywords',
'content' => 'Ключевые слова (keywords) через запятую'
)
);
 
drupal_add_html_head( $meta_keywords, 'meta_keywords' );
drupal_add_html_head( $meta_description, 'meta_description' );
}

В коде укажите название своей темы и описание, ключевые слова подходящие для главной страницы вашего сайта. Сохраните файл template.php после внесения изменений.

Удаление мета тега Generator

Мета тег Generator автоматически формируется Drupal. В нем содержится информация о текущей версии системы и дается ссылка на сайт drupal.org. Это плохо как с точки зрения безопасности, так и с точки зрения поискового продвижения сайта. Удалим его.

Заходим на сервер с помощью ftp клиета, переходим в каталог /includes и открываем на редактирование файл common.inc. Лучше всего это сделать в редакторе Notepad++, так как он подсвечивает синтаксис кода и делает работу с ним более удобной. Находим и удаляем следующий код:

// Show Drupal and the major version number in the META GENERATOR tag.
  // Get the major version.
  list($version, ) = explode('.', VERSION);
  $elements['system_meta_generator'] = array(
    '#type' => 'html_tag',
    '#tag' => 'meta',
    '#attributes' => array(
      'name' => 'Generator',
      'content' => 'Drupal ' . $version . ' (http://drupal.org)',
    ),
  );
  // Also send the generator in the HTTP header.
  $elements['system_meta_generator']['#attached']['drupal_add_http_header'][] = array('X-Generator', $elements['system_meta_generator']['#attributes']['content']);
  return $elements;

Сохраняем файл после внесения изменений. Мета тег Generator должен исчезнуть. Проверьте это:

  1. Откройте исходный код любой страницы сайта.
  2. С помощью стандартного поиска (Ctrl+F) попробуйте найти слово «Generator».
  3. Если поиск результата не даст, то все хорошо — тег удален.

Как-то много всего получилось, но иначе никак. Спасибо за внимание! Берегите себя.

Лучший способ выразить благодарность автору — поделиться с друзьями!

Узнавайте о появлении нового материала первым! Подпишитесь на обновления по email:

Следите за обновлениями в Twitter и RSS.

Drupal 8 and higher

To change the title of a page view, you actually need to change both the view title (which will change e.g. the <body><h1> content) and the default title of the current request’s matching route (which will change e.g. the <head><title> content.)

Since this change record, you should use Drupal’s CurrentRouteMatch service to find the current route, not any Symfony code. Either:

  1. procedural code: call Drupal::routeMatch(), or:
  2. object-oriented code: inject the current_route_match service (preferred).

For the purposes of just changing a view’s title, this can be done procedurally in a hook_views_post_render() in a custom module’s .module file:


use DrupalviewsViewExecutable;

/**
 * Implements hook_views_post_render().
 */
function mymodule_views_post_render(ViewExecutable $view) {
  $title = "My custom title";

  // Set the view title.
  $view->setTitle($title);
  // Set the route title.
  $route = Drupal::routeMatch()->getCurrentRouteMatch()->getRouteObject();
  $route->setDefault('_title', $title);
}

If you have a view and you want to be able to programmatically change the title of, you can do it by implementing hook_views_pre_render in your custom module:

function mymodule_views_pre_render(&$view) {
  if ($view->name == 'my_view_name' && $view->current_display == 'my_display_id') {
    // Here you can do any php you want to get the title you need for your view.
    $view->build_info['title'] = "My custom title!";
  }
}

If you are altering the query and you have argument substitutions affecting the title, you can change these in hook_views_query_alter:

function mymodule_views_query_alter(&$view, &$query) {
  if ($view->name == 'my_view_name' && $view->current_display == 'my_display_id') {
      // First substitution - you may want !1 or %2, etc
      $view->build_info['substitutions']['%1'] = $new_substitution;
    }
}

Views Displayed as Pages

Use this:

drupal_set_title('My custom title!');

Instead of:

$view->build_info['title'] = "My custom title!";

Submitted by admin on Wed, 02/20/2013 — 04:27

You may ask me: why to have page titles for views?

Views in Drupal, technically, are used to display a list of content. Translating to business language, it will be used for category pages. For example, if you build a shopping website in Drupal to sell mobile devices, you will use «views» to construct the page of Apple products (and also Samsung products, LG products, etc …)

These category pages are very important (second most after your homepage). You will definitely want they appear on top of Google search results for relating keywords. To achieve it, one of the best SEO practices is to set good focused titles for them.

When I developed the website for Exotic Voyages, a luxury travel agent, it has many category pages. They are pages for hotels, tours, destinations, cruises, photos etc … all are built by Drupal 7 views. The SEO team of Exotic Voyages required me to let them set custom titles for these pages.

A tour page built by Drupal views - Exotic Voyages website

An example of a view in Drupal

I thought it should have been a popular topic. I spent days and could not find a quick and strait forward solution. Fortunately, I finally found a solution for this problem: 

1. Simple Page Title

Simple Page Title is simple, but it does exactly what I need, to be able to set custom title for any pages, basing on URLs.

This module is not popular, only 500+ installs and its version for Drupal 7 is still in development mode. However, I tested it in my client website and found no problem with it.

After installation, the module appears on Admin > Structure > Simple Page Title. Just provide the path and the title you want, and click on Submit. That’s quite easy.

Using Simple page title module in Drupal

Using Simple Page Title

It works properly in conjunction with the famous Page title module. So if you can both set title patterns and custom title as you desire.

Note: if you like the simplicity of this module, you may want to see the Metatag quick module as well. It also enables you to set custom metatag for any URL.

2. On Drupal 6, use Nodewords Page Title

On my Drupal 6 websites, I use the Nodewords Page Title module. It is an addons to the Nodewords module and provides an additional tab to set custom page title for URLs.

Using Simple page title module in Drupal

Using Simple Page Title

Please be warned that this module only works with Nodewords 1.12-rc1 or 1.12-beta9.

3.Use views as attachment block

Another interesting solution which I found on this article on Digett is to make all pages on your website as nodes. Then, configure a view as a block and attach to a specific node.

That’s a clever way to work around the problem. Now you can set page titles and meta tags for nodes with ease, like I have describe on the previous article «Set Drupal page title and node title».

This article is written by . Enjoy!

  • Drupal Planet
  • custom page title drupal 7
  • drupal page title views
  • drupal views page title

Понравилась статья? Поделить с друзьями:
  • Как изменить swappiness
  • Как изменить timezone linux
  • Как изменить svs на dwg
  • Как изменить timeline framerate davinci resolve
  • Как изменить svg шрифт