0

I'm trying to generate a link as part of a string which will get sent by email. The link has to be styled to look like a button.

I'm doing this in a token event subscriber.

Here's my current code:

$url = Url::fromUri('https://google.com');
$link = new Link('Click me', $url);
$link = $link->toRenderable();
$link['#attributes'] = [
  'class' => ['nm-share', 'nm-share-' . $type_name],
  'target' => '_top',
  'style' => 'display:inline-block;width:213px;height:30px;color:#FFFFFF;text-decoration:none;text-align:center;padd  ing:15px 0px 0px;background:' . $colour . ';font:normal 17px/17px Arial, Helvetica, sans-serif;box-sizing:content-box;-webki  t-box-sizing:content-box;-moz-box-sizing:content-box;',
];

When the link is rendered it has the class and target attributes, but the style attribute is missing. How can I stop that from happening?

Converting my code to use an inline_template element seems like a messy solution.

The weird thing is if I put the same code in a drush script and run the script the style attribute does get rendered.

4
  • See Add inline style to render array attributes, without XSS filtering - short answer: You can't because this is filtered due XSS attacks. A workaround might be using an inline_template render element
    – Hudri
    Oct 5, 2022 at 14:28
  • Not really, I guess I could render my own anchor tag in an inline_template but I'd prefer to let the Link class do that for me.
    – Lambic
    Oct 5, 2022 at 14:30
  • after $link = $link->toRenderable() there is nothing left of a link class anymore, you are in the world of render arrays now. A link object with a method like setCssStyle() would be a horrible mix of concerns.
    – Hudri
    Oct 5, 2022 at 14:32
  • What I'm saying is I should be able to use the Link object to generate my render array then add attributes to it. Weirdly this works in drush php, but not in an event subscriber
    – Lambic
    Oct 5, 2022 at 14:47

1 Answer 1

0

Well this turned out to not be about render arrays at all.

I was using devel_debug() to send the rendered string to my drupal_debug.txt, and it turns out devel_debug() passes the text it receives through a text filter which strips out the style tag. The rendered string does in fact contain the style attribute.

To confuse my situation further, the rendered string was getting passed to another drupal instance via an api call, and that instance was also stripping out the style tags.

Ultimately this came down to symfony_mailer module stripping out style tags from the email body.

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.