1

So I have a situation where I have a core Link field on a node. I wanted to style that link with custom attributes, so I created a field.html.twig override to do that, only to find that the link itself is printed elsewhere. There doesn't appear to be a template or theme hook for the link; given that the core Twig debug functionality doesn't report a child template being invoked.

I tried pulling the URL out directly and rendering my own link, but that class (Drupal\Core\Url) isn't on the Twig whitelist, so getting the URL out will just cause a WSOD. There doesn't appear to be an Attributes object that I could add things into.

I could use theme_preprocess_field to call Drupal\Core\Url->toString() directly and store it in another variable, but I'd be throwing out whatever attributes are generated by default. I'd rather participate in however Drupal is rendering this link directly; or, if it's not extensible, at least know how to replicate what core does.

(For the record, the solution recommended in another question of using theme_preprocess_field to write attributes into #options does not appear to work.)

EDIT: As requested, here is the code I tried for a preprocess hook to add attributes:

function MYTHEME_preprocess_field(&$variables) {
    $element = $variables['element'];
    if ($element['#name'] == 'field_extra_links') {
        $variables['items'][0]['content']['#options']['attributes']['class'][] = 'Button';
    }
}
  • As far as the render array version goes, there are two ways: '#options' => ['attributes' => ['foo' => 'bar']] and '#attributes' => ['foo' => 'bar']. The link element preRenderLink method handles either. A preprocess does sound like the right way, if you can add the code to the question someone might be able to point out any problems – Clive Mar 7 '16 at 23:33
  • Added code example for what didn't work – Libertardian Mar 7 '16 at 23:49
  • Did you install Devel Kint? This should help give you some insight as to what is in the array. Also enabling Twig debug would give more insight as to what templates are available and or being used. – Danny Englander Mar 8 '16 at 3:24
  • Either use $variables['attributes'] or hook_form_alter. – user21641 Mar 8 '16 at 14:15
0

Answering my own question: the original suggestion was actually a valid solution; the way I had my theme configured meant that the hook wasn't loading. Stupid mistakes!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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