2

I'm currently creating a custom theme for a drupal 8 site and I'm putting a comment section for blog posts like :

<section class="comment-section">
    {{ content.comment }}
</section>

That puts in the comment section, but now I want to style it. I have twig debug enabled and to customize a page or view I usually look at the inspector/page source and there are comments recommending file names such as page--node--1.html.twig and such. Unfortunately for these fields when I look for the textarea or title input the only suggestions are, for example, ../form/textarea.html.twig. I can't use those because they will effect every other textarea on the site, so how do I figure out what to name my file for these specific inputs?

I'm going to put in a screenshot of my elements console in case it has something to do with that: enter image description here

2 Answers 2

1

Checkout the following module: Themable forms

It adds the following theme suggestions:

form-element--[form-id]--[element-type].html.twig
form-element--form-id--[form-id].html.twig
form-element--type--[element-type].html.twig
form-element.html.twig

Or use theme suggestions hooks to create / alter a theme suggestion. See the following link:

Working With Twig Templates

2
  • I played around with both answers, and this one was simpler and easier to work with! Thank you! Jun 1, 2017 at 20:39
  • @ConorBaumgart, yes, this is easier to work with. At first glance both answers seem to do the same thing. But they do not. They target different parts of the html markup.
    – 4uk4
    Jun 2, 2017 at 6:33
7

If you want to add a more specific template name to an input element use a theme name suggestions alter hook:

mytheme.theme

function mytheme_theme_suggestions_input_alter(&$suggestions, array $variables) {
  $element = $variables['element'];
  if ($element['#type'] == 'textfield' && strpos($element['#id'], 'edit-subject-') === 0) {
    $suggestions[] = 'input__textfield__subject';
  }
}

function mytheme_theme_suggestions_textarea_alter(&$suggestions, array $variables) {
  $element = $variables['element'];
  if (strpos($element['#id'], 'edit-comment-body-') === 0) {
    $suggestions[] = 'textarea__comment_body';
  }
}

You find more information here hook_theme_suggestions_HOOK_alter.

If you don't find the data you need in the elements variables, then you have to add it in the form build process, for example in a form alter hook. In this case the form build has already provided the necessary information in the element id.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.