How to add javascript to footer of OpenCart?

2 мин. на чтение

There is a special library, called Document, which is possible to found in system/library/document.php. By usuing it you can easy add javascript in any controller of OpenCart. Just follow those simple steps to do that:

  1. Add this string to index() part of any controller  $this->document->addScript('path/to/script.php');. This string will add new element to multidimensional array, which is possible to call in loop.
  2. Call all scripts from array via foreach from tpl, eg in header:
<?php foreach ($scripts as $script) { ?>
 <script src="<?php echo $script; ?>" type="text/javascript"></script>
 <?php } ?>

The attentive reader drew attention to the fact that in Paragraph 1 we use the word multidimensional in the context of an array. The bottom line is that if you look at the Document library code, you can pay attention that methods addScript  and getScripts using as parameter postion, by default set to header, this parameter gives us possibility to store scripts separately each other. So we are free to set it to footer. In this case, if you need to put script to footer of your OpenCart website, just do that:

In code of controller (index() section) put this: $this->document->addScript('path/to/script.php','footer');

Do not forget to check, that in code on footer controller there is this line:

$data['scripts'] = $this->document->getScripts('footer');

Finally, in related .tpl put this:

<?php foreach ($scripts as $script) { ?>
 <script src="<?php echo $script; ?>" type="text/javascript"></script>
 <?php } ?>

In a recent version of OpenCart 2.x mistake in code, word position was fixed. But here I’m using – postion as is in my testing OpenCart 2.3 to make code searching easly.

1 comment

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.