Notes

Dynamically adding Scripts, Stylesheets, and Links to a Template

Edit on GitHub

OpenCart

Compatibility: OpenCart 2.x

  • the benefit of dynamically loading it in templates is that it’ll only load when that template is being viewed. For example, the datetime picker only gets loaded when needed

In your controller (e.g. controller/account/register.php), inside the index() function

 1// $this->document->setTitle($this->language->get('heading_title'));
 2
 3// Scripts
 4// addScript($href, $postion = 'header')
 5$this->document->addScript('catalog/view/javascript/jquery/datetimepicker/moment.js');
 6$this->document->addScript('catalog/view/javascript/jquery/datetimepicker/bootstrap-datetimepicker.min.js');
 7
 8// Styles
 9// addStyle($href, $rel = 'stylesheet', $media = 'screen')
10$this->document->addStyle('catalog/view/javascript/jquery/datetimepicker/bootstrap-datetimepicker.min.css');
11
12// Links 
13// addLink($href, $rel)
14addLink($href, $rel)

In your template template/common/header.tpl

 1// Load Scripts
 2<?php foreach ($scripts as $script) { ?>
 3<script src="<?php echo $script; ?>" type="text/javascript"></script>
 4<?php } ?>
 5
 6// Load Styles
 7<?php foreach ($styles as $style) { ?>
 8<link href="<?php echo $style['href']; ?>" type="text/css" rel="<?php echo $style['rel']; ?>" media="<?php echo $style['media']; ?>" />
 9<?php } ?>
10
11// Load Links
12<?php foreach ($links as $link) { ?>
13<link href="<?php echo $link['href']; ?>" rel="<?php echo $link['rel']; ?>" />
14<?php } ?>