Yii 1.1: CSS, JS and image URL shortcut methods


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.

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:

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.

Total 2 comments

#465 report it
mindplay at 2010/05/24 08:07pm
Personal preference

In the end, there are as many different ways to do this as there are developers - and these extensions are so small and easy to use, it's really a matter of personal preference.

I say, do whatever makes you comfortable :-)

#832 report it
~CODER~ at 2010/02/22 01:40am
Some optimization...


What I think is that there's no need to double call things like that Html::cssFile(Html::cssUrl('reset.css'));

It's obvios, that is you call cssUrl, you also call cssFile. So it would be much more readable if you also provide public function like Html::cssFileUrl('reset.css');

Or, even better, for several css files being loaded in sequence, there should be something like that: Html::cssFileUrl(array('reset.css','typography.css','main.css','form.css'));

The same approach we can use for eirther image and js things.

Leave a comment

Please to leave your comment.

Write new article
  • Written by: jonah
  • Category: Tutorials
  • Yii Version: 1.1
  • Votes: +2 / -2
  • Viewed: 26,501 times
  • Created on: Sep 2, 2009
  • Last updated: Jun 30, 2012
  • Tags: URL