Sign up ×
Drupal Answers is a question and answer site for Drupal developers and administrators. It's 100% free, no registration required.

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.

share|improve this question
    
You can use drupal_add_js() function with the 'setting' type. there is an example –  Jack-PL Jun 13 '13 at 21:28

1 Answer 1

up vote 2 down vote accepted

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

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.