1

I enabled twig debug and realized I needed to add block--search.html.twig to my theme. Then I used dump(content) to see if I could add a placeholder to search input field

{% extends "core/modules/block/templates/block.html.twig" %}
{% block content %}
  {{ dump(content) }}
  {{ content }}
{% endblock %}

How can I change the content array and add a new '#placeholder'=>'bla' to the search input?

dump(content) returns something like this:

array (size=23)
  '#action' => string '/search/node' (length=24)
  '#method' => string 'get' (length=3)
  'keys' => 
    array (size=26)
      '#type' => string 'search' (length=6)
      '#title' => string 'Search' (length=6)
      ...
  • I don't think you will want to put extends in a control tag as you have: {% extends "core/modules/block/templates/block.html.twig" %} This will throw an error in the latest iteration of Drupal 8, and in any case is not required to override the default template with your custom theme. – forest Jul 31 '14 at 4:53
5

Altering forms in Drupal 8 is the same as in Drupal 7 - you have:

Always use an alter/preprocess hook to change variables before they get to the template file, it's bad practice to change them once you're in the template file itself.

  • Thank you, I was so turned on by twig in drupal that I forgot about form_alter. But if I had to twig a really small change, that would have been something like '{% set content.keys = content.keys|merge({'#placeholder' : 'foo'}) %}'? – Pouya Sanooei Jul 2 '14 at 9:41
  • 1
    Theoretically yes...that would work fine for a placeholder/class/etc, but if you were altering anything more complicated (the "required" status of the field, for example), changing the value in the template wouldn't persist that information back to the original form object, so you might end up with inconsistencies. As a general rule: keep logic out of templates :) – Clive Jul 2 '14 at 9:44

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.