1

I'm creating a custom block and I'd like to add some Javascript to it. I'm using a Render Array to add the Javascript to the page, which works fine, I'm then trying to add some variables to the Render Array for the Javascript to use.

This is what my Render Array looks like

$content = array(
  '#slides' => $slides,
  '#theme' => 'slider_block',
  '#attached' => array(
    'js' =>
      array(
        drupal_get_path('module', 'single_slider') . '/js/test.js' => array(
          'type' => 'file',
        ),
      )
  )
);

$content['#attached']['js'][] = array(
  'data' => array('word' => 'world'),
  'type' => 'setting'
);

return $content;

I'm then trying to access the variable in the Javascript (test.js) file using the following.

console.log(Drupal.settings);

At the moment this just returns with an empty object. If someone could point me in the right direction I'd appreciate it very much.

Thanks in advanced.

1
  • You can use drupal_add_js() function with the 'setting' type. there is an example Commented Jun 13, 2013 at 21:28

1 Answer 1

4

Ok I've managed to solve it myself.

For anyone that is interested my Render Array now looks like this.

    return array(
        '#slides' => $slides,
        '#theme' => 'slider_block',
        '#attached' => array(
            'js' => array(
                array('data' => array('word' => 'world'), 'type' => 'setting'),
                drupal_get_path('module', 'single_slider') . '/js/tes.js'
            ),
        )
    );

And my Javascript file (test.js) now looks like this.

(function($)
{
    //console.log(Drupal.settings.word) //This won't work and will return with undefined.
    $(function()
    {
        alert('Hello ' + Drupal.settings.word);
    });
}(jQuery));
2
  • 1
    Would it be better to namespace the data you are passing? Something like array('data' => array('mymodule_word' => 'world'), 'type' => 'setting') Does that work? Commented Apr 9, 2015 at 20:36
  • 1
    I found my answer. You should namespace and this link drupal.org/node/304258 shows you how. Commented Apr 9, 2015 at 21:01

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.