Skip to main content
3 of 3
Better recommend inline_template instead of html_tag
leymannx
  • 18.8k
  • 6
  • 72
  • 126

If you want to alter html, generally you'll be working with hook_preprocess_hook or a twig template override. This is the case for views as well. In the case of views, the template that renders the title is views-view.html.twig.

EDIT: Fastest way is just to use #markup

function my_module_preprocess_views_view(&$variables) {
  $variables['title'] = [
    '#markup' => 'test - <b>My new Title</b>'
  ];
}

So if you wanted to render the title with a b tag, you could do:

function my_module_preprocess_views_view(&$variables) {
  $existing_title = $variables['title'];
  $variables['title'] = [
    '#type' => 'inline_template',
    '#template' => '<b>{{ title }}</b>',
    '#context' => [
      'title' => $existing_title,
    ],
  ];
}

However, it's maybe not ideal to use tags for presentation and better to use classes and CSS styling. If you just want to add a CSS class to target, you could do a similar thing:

function my_module_preprocess_views_view(&$variables) {
  $existing_title = $variables['title'];
  $variables['title'] = [
    '#type' => 'container',
    '#attributes' => [
      'class' => [
        'views-title', // or whatever 
      ],
    ],
    '#value' => $existing_title
  ];
}

Both #container and #inline_template are render elements, and there are a lot available to you.

Of course, depending on what your theme and other modules are doing, the existing $variables['title'] might not just be a string, so you may need to adjust accordingly.

Mrweiner
  • 2k
  • 4
  • 26
  • 49