1

This is a part of my script in template file where php code is used to generate js field of objects:

<?php $count = count($events); $counter = 1; ?>

<script>
  var events = [

  <?php foreach($events as $event) { ?>

    {
      date: '<?php echo $event['date']; ?>',
      linkTarget: "_blank",
      content: "<?php echo $event['content']; ?>",
      class: "<?php echo $event['class']; ?>"
    }
    <?php if($counter!=$count) { echo ','; $counter++; } ?>
  <?php } ?>

  ];
<script>

I know that we can add js variable by drupal_add_js(array('myModule' => array('key' => 'value')), 'setting'); but how can we create the same js array as in example above in order not to use php code in js?

2

You can pass an array to JS like this:

drupal_add_js(array('my_module' => array('events' => $events)), 'setting');

In javascript you can get the values like this:

Drupal.settings.my_module.events;
| improve this answer | |
0

You can try something like this in your custom module:

// build your associative array into $events variable
$events = json_encode(join(',', $events);
drupal_add_js(array('custom_module' => array('events' => $events)), 'setting')

And then in your template:

<?php print $events; ?>
| improve this answer | |
  • This does not work. $events = json_encode(join(',', $events); returns string "Array, Array, Array, Array, Array, Array". Btw. I need to use Drupal.settings.my_module.events; instead of <?php print $events; ?> – Incredible Dec 5 '16 at 15:15

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.