Referencing static resources where the name is not known at compile time

PS Note that the Dynamic References to Global Variables feature in Spring ’12 addresses this problem.

If you have a static resource such as an image that you want to display in a page there is a well documented method of referencing that static resource – see e.g. Delivering Static Resources with Visualforce. If the static resource is named “MyResource”, that resource is referenced using “$Resource.MyResource”. But this relies on the name being known at Visualforce page compilation time and the compilation also verifies that the static resource exists. If you want to provide the static resource name dynamically from a controller property there appears to be no way to do it. (In my case I wanted the name of a customer-specific ZIP file containing a help system to be configurable via a custom setting.)

By inspection (and as described in the above link), “$Resource.MyResource” results in a reference in the HTML of the form “/resource/1319816508000/MyResource”. With a bit of rooting around, that observation leads to this code:

public String myResource {
    get {
        String namespace = null;        
        String name = 'MyResource';
        StaticResource sr = [
                select LastModifiedDate
                from StaticResource
                where NamespacePrefix = :namespace
                and Name = :name
                limit 1
        return '/resource/' + sr.LastModifiedDate.getTime() + '/' + (namespace != null ? namespace + '__' : '') + name;

which so far has worked for me.


5 thoughts on “Referencing static resources where the name is not known at compile time

  1. Plian old /resource/MyResource also works if the static resource isn’t changed (or you wait a few hours for the cache to clear after such a change). The timestamp is only needed to get the right version of a changing resource.

  2. Last question, in your opinion, there is a way or a command to generate a static resource and fullfill it with a image by a visuapage?

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s