在 drupal8 中的 Twig 模板中渲染表单

Man*_*rth 3 drupal drupal-8

我目前正在使用 drupal 8,并且我已经使用表单 api 创建了表单,

Module目录下的以下代码

  // module/src/Form/ContributeForm

  class ContributeForm extends FormBase {

  public function getFormId() {
     return 'amazing_forms_contribute_form';
  }

  public function buildForm(array $form, FormStateInterface $form_state) 
  {
      $form['title'] = array(
           '#type' => 'textfield',
           '#title' => t('Title'),
           '#required' => TRUE,
      );
      $form['video'] = array(
           '#type' => 'textfield',
           '#title' => t('Youtube video'),
      );
      $form['video'] = array(
          '#type' => 'textfield',
          '#title' => t('Youtube video'),
      );
     $form['develop'] = array(
          '#type' => 'checkbox',
          '#title' => t('I would like to be involved in developing this 
           material'),
    );
    $form['submit'] = array(
          '#type' => 'submit',
          '#value' => t('Submit'),
);
return $form;
}

public function validateForm(array &$form, FormStateInterface $form_state) {
}

public function submitForm(array &$form, FormStateInterface $form_state) {
}
}
Run Code Online (Sandbox Code Playgroud)

现在我需要在树枝模板中渲染上面的变量,如下所示

 //themes/page.html.twig

 <body>
    {{form.title}}
    {{form.video}}
    {{form.video}}
 </body>
Run Code Online (Sandbox Code Playgroud)

树枝将在主题文件夹下。是否可以在 page.html.twig 文件中获取变量?

小智 5

通过 Twig 呈现和自定义表单的最佳方式是在表单中使用$form['#theme']值。下面的例子:

module_name/scr/Form/your_form.php

public function buildForm(array $form, FormStateInterface $form_state){
       .....
       .....

       $form['#theme'] = 'your_form_theme';

       return $form;
}
Run Code Online (Sandbox Code Playgroud)

模块名称/form.module

function form_theme() {

    $themes['your_form_theme'] = ['render element' => 'form'];

    return $themes;
}
Run Code Online (Sandbox Code Playgroud)

剩下的是创建您的自定义树枝并插入您的表单字段。

module_name/templates/your-form-theme.html.twig

<body>
    {{form.field_1}}
    {{form.field_2}}
    {{form.field_3}}
 </body>
Run Code Online (Sandbox Code Playgroud)

希望对你有帮助!