CSS, JS and image URL shortcut methods

You are viewing revision #8 of this wiki article.
This is the latest version of this article.
You may want to see the changes made in this revision.

« previous (#7)

Below I have created an Html helper with methods to help me locate directories of my assets dynamically. Such assets may include CSS, JavaScript and images.

<?php
class Html
{
	/**
	* Makes the given URL relative to the /image directory
	*/
	public static function imageUrl($url) {
		return Yii::app()->baseUrl.'/images/'.$url;
	}
	/**
	* Makes the given URL relative to the /css directory
	*/
	public static function cssUrl($url) {
		return Yii::app()->baseUrl.'/css/'.$url;
	}
	/**
	* Makes the given URL relative to the /js directory
	*/
	public static function jsUrl($url) {
		return Yii::app()->baseUrl.'/js/'.$url;
	}
}

Methods like the above can be useful for including assets on the client-side. You can use it like in the following:

<?php
echo Html::cssFile(Html::cssUrl('reset.css'));
echo Html::cssFile(Html::cssUrl('typography.css'));
echo Html::cssFile(Html::cssUrl('main.css'));
echo Html::cssFile(Html::cssUrl('form.css'));
?>

This is much cleaner and shorter then prefixing the URLs manually. Also, if you ever wish to move the directory of some sort of asset, all you need to do is modify the corresponding method in Html.

2 1
4 followers
Viewed: 36 692 times
Version: Unknown (update)
Category: Tutorials
Tags: URL
Written by: jonah
Last updated by: jonah
Created on: Sep 2, 2009
Last updated: 11 years ago
Update Article

Revisions

View all history

Related Articles