0

Kohana 3 Multiple Scripts and Styles Extension

Posted (Updated ) in PHP

In Kohana 2, html::script() and html::stylesheet() accepted an array or string as their first arguments. This allowed you to easily add multiple script and style tags simultaneously without needing to write several lines of redundant code. Kohana 3 has removed this useful functionality so I thought I’d write a very quick extension to add it back in. The following adds HTML::scripts() and HTML::styles() functions (Kohana 3 slightly renamed their functions to HTML::script() and HTML::style() respectively).

Simply add the following file html.php to your /classes directory:

<?php defined('SYSPATH') or die('No direct script access.');
 
class HTML extends Kohana_HTML {
	public static function scripts(array $scripts, $attributes=array(), $index = FALSE)
	{
		$response = '';
 
		//Data sanitisation
		$index = $index ? TRUE : false;
		if ( !is_array($attributes) ) $attributes = array();
 
		foreach ( $scripts as $script )
			$response .= html::script($script, $attributes, $index);
 
		return $response;
	}
 
	public static function styles(array $styles, $attributes=array(), $index = FALSE)
	{
		$response = '';
 
		//Data sanitisation
		$index = $index ? TRUE : false;
		if ( !is_array($attributes) ) $attributes = array();
 
		foreach ( $styles as $style )
			$response .= html::style($style, $attributes, $index);
 
		return $response;
	}
}

Download: html.php

Usage:

<?php
echo HTML::styles(array(
	'assets/css/reset',
	'assets/css/styles',
);
echo HTML::scripts(array(
	'assets/js/jquery',
	'assets/js/jquery.ui.all',
);
?>

Note: Both functions accept the latter 2 parameters available in Kohana 3 HTML::script() and HTML::style(). If given, these arguments will be applied to every element in the provided array.