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.

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));
  • 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? – Alex Finnarn Apr 9 '15 at 20:36
  • 1
    I found my answer. You should namespace and this link drupal.org/node/304258 shows you how. – Alex Finnarn Apr 9 '15 at 21:01

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.