0

I need to pass a variable to a library called on a Twig template, is this possible?

{{ attach_library('theme/some-library') }}
3
  • You could also do this from a preprocess hook. – Kevin Apr 24 '18 at 22:07
  • 1
    You want a variable that will be read as Javascript in the client's browser? You could print a script tag with the variable. And the library would read it from the DOM. – BWagner Apr 24 '18 at 22:32
  • Right, I was wondering if there was a more fancy way of doing it. – Flupkear Apr 25 '18 at 18:28
3

.module

/**
 * Implements hook_ENTITY_TYPE_load()
 */ 

function my_module_node_load($nodes) {
    foreach ($nodes as $node) {
      if ($node->getType() == 'article') { // is of article content type
        $data_passer = &drupal_static('my_module_node_field_name');
        // use &drupal_static to pass value between hooks. 
        $data_passer = $node->field_name->value;
      }
    }
}

/**
 * Implements hook_page_attachments()
 */
function my_module_page_attachments(array &$attachments) {
    if (!empty(&drupal_static('my_module_node_field_name'))) {
      $data_passer = &drupal_static('my_module_node_field_name'); 
      $node_field_name = $data_passer;
      $attachments['#attached']['drupalSettings']['my_variable'] = $node_field_name;     
    }
  }
}

.js

(function ($, Drupal, drupalSettings) {
  Drupal.behaviors.my_behaviour = {
    attach: function (context, settings) {

      alert(drupalSettings.my_variable); //alerts passed in node field_name

    }
  };
})(jQuery, Drupal, drupalSettings);
2
  • Thanks, but I was wondering if there is a way of doing it directly from the template, although I ended up using a preprocess hook. – Flupkear Apr 25 '18 at 18:29
  • @Flupkear from template file there isn't, unless you print the value in an attribute and then pick it up with jQuery. Ex: <div class"something" variable="{{ content.field_variable.0 }}"> {{ content.field_some_field }} </div> and in jQuery var variable = $('.something').attr('variable'); – No Sssweat Apr 26 '18 at 20:44
-1

I have passed my variable in twig like this:

{{ attach_library('theme/library' ~ variable ) }}

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.