I am trying to pass my paragraph field data from Drupal to a component that I have created in Twig. My component echos out data like so:

<p class='my-custom-class'>{{ my_var }}</p>

In my template file, I am passing data to the component like so:

{% include '@components/my-component-name.twig' with {
   my_var: content.field_my_var_name.0
} %}

However, when this loads in my browser, what I am getting is:

<p class='my-custom-class'></p>
<p>The contents of my var.</p>

How can I load the contents of my_var into my <p> tag without getting another tag injected?

  • 2
    Change the underlying field type, do not use a formatted text field, but use a plain/unformatted text field instead. – Hudri Nov 12 '19 at 11:34
  • 1
    Not 100% sure, but you may be able to create a Text Format that only allows some inline elements, like <b>, <i>, <u>, and not the block level ones, and don't convert newlines to <p>. – mpdonadio Nov 12 '19 at 14:44

Does your field contain other <p> tags you want to preserve? Or just this one in the beginning and end? If you don't need to preserve other <p> tags, you could simply use Twig's |striptags filter.

<p class='my-custom-class'>{{ my_var|striptags('<p>') }}</p>

Or as @Hudri suggested in the comments under your question you may change the field type to something other than formatted text. Or maybe try changing the text format to plain.

  • Thanks - seems a bit redundant for me to go back through all my components and strip out the tags, but that does work fine thanks! Do you know how I can dump/print out all of the field variable names that are available to use in the template by any chance? – party-ring Nov 12 '19 at 12:27
  • @party-ring – Install the Devel sub-module Kint and then put {{ kint() }} in your template. Flush cache, and then you'll get all available variables/object onscreen. – leymannx Nov 12 '19 at 12:34
  • 1
    @party-ring – Yeah stripping tags in the template actually shouldn't be the preferred way. Better have an unformatted text field in the first place. But yeah, that's not easily to be swapped on an existing installation. – leymannx Nov 12 '19 at 12:36

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.