I have a form like:

 public function buildForm(array $form, FormStateInterface $form_state, $short_title = '') {
$title = 'xyz';

In my .module file, I have a theme function:

function ip_mcq_theme() {
  return [
    'take_mcq_form' => [
      'render element' => 'form',

How to get form variables like $short_title and $title mentioned in form build function in my take-mcq-form.twig.html file?


Put the custom variable in a key with a '#', so that the formbuilder doesn't try to render this as a form element.


  $form['#myvars']['var1'] = 'xyz';

In twig you can access the variable in element:


  {{ element['#myvars'].var1 }}

If you set a template in #theme of the form build


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

you get a second template inside of form.html.twig, where you can access the variable in form:


  {{ form['#myvars'].var1 }}
| improve this answer | |

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.