Dynamically get the path to a static resource

I would like to control which style sheet is included in my Visualforce page at load time, so instead of having:

<link rel="stylesheet" type="text/css" href="{!$Resource.eng_mobile}" />

I would like:

<link rel="stylesheet" type="text/css" href="{!myTheme}" />

So, in my page controller, what is the syntax to get the path to a static resource. Something like this, maybe?

String myTheme = $Resource.getPath(lang + '_' + size);

Searching for “$Resource” on developerforce.com gives at least 54,000 results.

Edit:

For my use case I probably need to get the resource url in the controller:

   if (!customCss) {
      myTheme = $Resource.getPath(lang + '_' + size);
   } else {
      myTheme = ApexPages.currentPage().getParameters().get('css');
   }

Answer

You can get the URL using the following util class.

 public class StaticResourceURL
    {
        // Pass the resource name
        public static String GetResourceURL(String resourceName){

            // Fetching the resource
            List<StaticResource> resourceList= [SELECT Name, NamespacePrefix, SystemModStamp FROM StaticResource WHERE Name = :resourceName];

            // Checking if the result is returned or not
            if(resourceList.size() == 1){

               // Getting namespace
               String namespace = resourceList[0].NamespacePrefix;
               // Resource URL
               return '/resource/' + resourceList[0].SystemModStamp.getTime() + '/' + (namespace != null && namespace != '' ? namespace + '__' : '') + resourceName; 
            }
            else return '';
        }
    }

This is a excerpt from this blog http://forceguru.blogspot.in/2012/05/static-resource-url-in-apex.html

Attribution
Source : Link , Question Author : JannieT , Answer Author : sanchit

Leave a Comment