I have a custom block with text in the body field. I need to prepend some text to this body field, either using php in a theme_hook function or in a twig file. How can I get just the text of the body field of a custom block so that I can alter it?


Here are three possible approaches to achieve your desired effect.

1. Hardcoding into a twig template for the custom block

If you don't need to modify the actual content defined within the body field of the custom block, and just want to hardcode the prepended text before the body content, creating a custom twig template for the block itself is probably easier for maintaining in the long run. This way it's easy to find and modify without the need to do any theme_hook function editing.

  • In your theme's template folder, add a block--[machinename-with-hyphens].html.twig template.
  • Copy the contents of the block.html.twig template that already exists in your theme or from a theme included with Drupal Core such as Bartik or Classy (/core/themes/classy).
  • Then in the template, add your markup and desired text before the {% block content %} section. If your custom block has more than a body field, you can also render just the body field data using {{ content.body }}, and the other fields as {{ content.[field_machinename] }}

2. Hardcoding the text into a theme hook preprocess function

If you would rather avoid setting up a custom one-off twig template for the block and just want to hardcode the prepended text using a preprocess hook, you could:

  • Add a [custom_theme]_preprocess_block function. If your function doesn't explicitly inlcude the block's machine name in the function name, be sure to check the block machine name before prepending text and setting the content.
  • Create a variable for your custom markup/formatted text.
  • Concatenate that with the existing block content.
  • Set the 'content' variable in the preprocess function

See Drupal.org documentation for template_preprocess_block or hook_preprocess_block

3. Recommended Approach: no template or preprocess code required.

The easiest method to approach this might be to just add a custom field to the custom block type with the default value reflecting the prepended text. To do this:

  • Go to Structure > Block Layout
  • Select the Custom Block Library tab
  • Select Block Types
  • Choose Edit next to your existing custom block type or Add custom block to add a new custom block type.
  • In the Manage Fields section, add a field for the predefined text (or markup) to prepend.
  • In the Manage Display section, set the desired order for the fields to render.

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.