0

I am using a Twig template to render a form that has a variable number of elements.

Each element's key in the form is sequential integer.

So in my template, I can do this:

{% for item in form|children %}
  {{ item }}
{% endfor %}

However, then I have a broken form, because there's no <FORM> HTML element, or the form ID for submission.

I've looked at twig templates for forms in core, but they all work with fixed elements, so they're able to do something like this, seen in modules/content_moderation/templates/entity-moderation-form.html.twig:

{{ form|without('current', 'new_state', 'revision_log', 'submit') }}
  • There are two different form templates: 1. The outer #theme_wrapper for the form tag. 2. The inner #theme for the form elements (shown in your example and explained here drupal.stackexchange.com/a/245427/47547). – 4k4 Aug 10 at 19:37
0

If you look at form.html.twig in the Drupal Core's system module, you'll see:

{#
/**
 * @file
 * Default theme implementation for a 'form' element.
 *
 * Available variables
 * - attributes: A list of HTML attributes for the wrapper element.
 * - children: The child elements of the form.
 *
 * @see template_preprocess_form()
 *
 * @ingroup themeable
 */
#}
<form{{ attributes }}>
  {{ children }}
</form>

Using this as a guide, you should be able to do:

<form{{ attributes }}>
  {% for item in form|children %}
    {{ item }}
  {% endfor %}
</form>

children is already a variable in the template so you can just use it like:

<form{{ attributes }}>
  {% for item in children %}
    {{ item }}
  {% endfor %}
</form>

But if you're not wrapping the individual children, why even use a custom template? Why not just use the default form.html.twig.

| improve this answer | |
  • I've tried overriding core's form.html.twig and 1. for item in children doesn't work -- looks like it's not iterable and dumping it shows it's a Drupal\Core\Render\Markup object with just a 'string' property; 2. form is NULL, so for item in form|children won't work. – joachim Aug 12 at 10:02
  • This is what you would expect from a theme wrapper like form.html.twig. This wraps the <form> tag around children (which is already rendered). Do not confuse it with a #theme template like the template you've mentioned in the question entity-moderation-form.html.twig – 4k4 Aug 12 at 16:39

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.