We can add the JS and CSS in the page-front.tpl file but generally you wouldn't do that as the TPL in question may be used on multiple pages but your CSS/JS is only required on say a specific page (in the case of the page-front template this is only used on the front page but this is an exception)

Ways of putting CSS & JS on your page

1. Generic template file: template.php

You will see this done but this then applies to all pages (although conditional tests can be done, e.g. if (arg(0) == ...) {...}.

Couple of things to note - primarily multiple ways to skin a cat, note the use of variables, drupal_add_js/css, etc

2. Page template: page.tpl

Extract below is from the Garland theme

  <?php
  ?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
  <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="<?php print $language->language ?>" lang="<?php print $language->language ?>" dir="<?php print $language->dir ?>">

    <head>
      <?php print $head ?>
      <title><?php print $head_title ?></title>
      <?php print $styles ?>
      <?php print $scripts ?>
      <!--[if lt IE 7]>
        <?php print phptemplate_get_ie_styles(); ?>
      <![endif]-->
    </head>

Notice you can add your own scripts into the head etc - but this is not necessarily the recommended approach, you could use the theme info file instead

3. Theme info file

This will apply to all pages also, below is an example:

…
stylesheets[all][]        = css/html-reset.css
stylesheets[all][]        = css/wireframes.css
…
scripts[] = js/cybernet.min.js
…

4. Module info file:

Again this will then always be loaded as long as the module is enabled (example below is from a Drupal theme but the principle is the same):

name = Garland
description = Tableless, recolorable, multi-column, fluid width theme (default).
version = VERSION
core = 6.x
engine = phptemplate
stylesheets[all][] = style.css
stylesheets[print][] = print.css

5. In the module:

If your CSS/JS is only to appear on specific pages then this would normally be the preferred method (except where the site was done via a build and you only had theming, in which case you would do it via TPL)

So assuming we had a particular callback function for our page, we could then do:

  // in the module callback function
  $path = drupal_get_path('module', <module name>);
  drupal_add_css($path.'/css/<mycssfile>');
  drupal_add_js($path.'/js/<myjsfile>');
  // for the theme
  $path = drupal_get_path('theme', <theme name>);
  drupal_add_css($path.'/css/<mycssfile>');
  etc etc

"More than 1 way to skin a cat"

So as you can see there are lots of ways of doing it, just choose the way that is most appropriate to your requirements.

Tags: