I want to override the HTML string returned by core using a custom module that replaces $content['#markup'], or the entire $content array returned by HtmlResponse::setContent().

I can override Response::setContent() by calling HtmlResponse::setContent(). Exactly how do I add this to a custom module, for example implementing a service?

My goal is altering all the <a> tags to add a <span> tag to the ones that links to downloadable files.

  • You should tell us what your overall goal is, not just how you are trying to accomplish it. This post needs more details.
    – Jaypan
    Aug 15, 2021 at 15:36
  • @Jaypan - I want to run a REGEX on the rendered HTML string that will modify all the <a> tags by adding a <span> to the ones that link to downloadable files. I have the regex, Too many links from too many different sources to do this effectively in the theme so I want to try this approach
    – wildfeed
    Aug 15, 2021 at 16:00
  • do you want to change a Form or Controller output?
    – hoanns
    Aug 15, 2021 at 18:35

2 Answers 2


If you want to change the output of a form see hook_form_alter

If you want to change the output of controllers see this answer. You can also subscribe to other Kernel Events with that method and should be able to alter any output your site creates. (kernel.response is probably what you need)


If you want to act on the rendered HTML of a render array rather than the structured content array before rendering, use a #post_render callback. See How to alter page content?

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.