I have a View that lists entities. One of the fields is the entity label field, which is set to output a link to the entity itself. I would like to add attributes to the <a> tag to grab later with a jQuery plugin.

I can use template_preprocess_views_view_field() and hook_views_pre_render() to get the rendered markup and alter it there, but it's very dirty and not something I'll consider. I could also create a specific theme suggestion and field template and do it that way, but I don't want to rely on something that's potentially editable or changeable. It needs to be as generic as possible.

Is there a clean solution for this?

  • I would recommend you inspect element and see what the field template suggestion is. Theme that file to your needs. Editing an existing template will not add any overhead. Feb 5, 2019 at 17:40
  • If you can't find this option in Views UI then the cleanest way is to install a contrib or custom field handler plugin which provides this option.
    – 4uk4
    Feb 5, 2019 at 19:29
  • @4k4 I want to do it programmatically. A field handler seems overkill for this, since it should be as generic as possible. Feb 5, 2019 at 19:56
  • By custom field handler I meant programming a field handler, but you wouldn't start from scratch, you would extend the existing handler.
    – 4uk4
    Feb 5, 2019 at 20:18
  • After checking the existing field handlers I think you used the generic option "Link to the Entity", not a label specific one. So it might be easier to add a custom views field plugin from scratch. See the answer.
    – 4uk4
    Feb 6, 2019 at 8:08

1 Answer 1


Generate the scaffolding of a Views field plugin with Drupal Console

drupal generate:plugin:views:field

and put the link in the render() method generated by the command above:

  public function render(ResultRow $values) {
    if ($entity = $values->_entity) {
      return [
        '#type' => 'link',
        '#title' => $entity->label(),
        '#url' => $entity->toUrl(),
        '#attributes' => [
          'class' => ['foo'],

After clearing the cache you'll find the new field plugin when adding a field to the FIELDS list.

Your Answer

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

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