Search code examples
symfonywebpacktwigglobalexternal

Use Twig variables in external js file


I am setting up webpack for my symfony project and I want to have page specific javascript files. I need to use twig filters such as {{ form.licenseText.vars.id }} in my external js file that I will build in webpack. Any help here?

I tried setting up the variable and calling tag after that which doesn't seem to work.

$(document).ready(function(){
  $.trumbowyg.svgPath = '/img/trumbowyg-icons.svg';

  var trumbowyg_config = {
    btns: [
      ['formatting'],
      'btnGrp-semantic',
      ['link'],
      ['insertImage'],
      'btnGrp-lists',
      ['horizontalRule'],
      ['removeformat'],
      ['viewHTML'],
      ['fullscreen']
    ]
  };

  $('#{{ form.descriptionText.vars.id }}').trumbowyg(trumbowyg_config);
  $('#{{ form.licenseText.vars.id }}').trumbowyg(trumbowyg_config);

  /* toggle text boxes in respect to the auto update settings */
  $('#{{ form.descriptionTextAutoUpdate.vars.id }}').on('change', function() {
    var au = $('input[name="{{ form.descriptionTextAutoUpdate.vars.full_name }}"]:checked').val() == '1';
    var el = $('#descriptionText_div');
    au ? el.hide() : el.show();
  });
  $('#{{ form.licenseTextAutoUpdate.vars.id }}').on('change', function() {
    var au = $('input[name="{{ form.licenseTextAutoUpdate.vars.full_name }}"]:checked').val() == '1';
    var el = $('#licenseText_div');
    au ? el.hide() : el.show();
  });

I would like to access these twig variables in my external js file as shown above in the code.


Solution

  • You can use two tricks for this.

    a. Use classes or specific attributes in your form elements, and access to them with global selectors.

    <?php
    
    namespace App\Form;
    
    class MyForm extends AbstractType
    {
      public function buildForm(FormBuilderInterface $builder, array $options)
      {
           $builder->add("descriptionText", null, [
               "attr" => [ "class" => ["trumbowygable"]],
               ...
           ]) ;
    
           ... or ...
    
           $builder->add("otherField", null, [
               "attr" => [ "data-other-thing" => 1]],
               ...
           ]) 
    
    
      }
    }
    

    And JS looks like ...

    $('input.trumbowygable').trumbowyg(trumbowyg_config);
    // or
    $('input[data-other-thing]').on("someEvent", bla bla bla);
    

    b. Create a global javascript function that receive id elements by parameters.

    function buildTrumbowyg(id_one, id_two) {
        $('#' + id_one).blaBlaBla( ... )
    }