Sunday, January 25, 2015

Referencing a Static Resource in Visualforce Pages?

Referencing a Static Resource in Visualforce Pages?


The way you reference a static resource in Visualforce markup depends on whether you want to reference a stand-alone file, or whether you want to reference a file that is contained in an archive (such as a .zip or .jar file):


  • To reference a stand-alone file, use $Resource.<resource_name> as a merge field, where <resource_name> is the name you specified when you uploaded the resource. For example:
<apex:image url="{!$Resource.TestImage}" width="50" height="50"/>
                                    OR
<apex:includeScript value="{!$Resource.MyJavascriptFile}"/>
  • To reference a file in an archive, use the URLFOR function. Specify the static resource name that you provided when you uploaded the archive with the first parameter, and the path to the desired file within the archive with the second. For example:
<apex:image url="{!URLFOR($Resource.TestZip,'images/Bluehills.jpg')}" width="50" height="50"/>
                                       OR
<apex:includeScript value="{!URLFOR($Resource.LibraryJS, '/base/subdir/file.js')}"/>
  • You can use relative paths in files in static resource archives to referto other content within the archive.For example, in your CSS file, named  styles.css, you have the following style:
          table { background-image: img/testimage.gif }

When you use that CSS in a Visualforce page, you need to make sure the CSS file can find the image. To do that, create an archive (such as a zip file) that includes styles.css and img/testimage.gif.  Make sure that the path structure is preserved in the archive. Then  upload the archive file as a static resource named “style_resources”.  Then, in your page, add the following component: 

<apex:stylesheet value="{!URLFOR($Resource.style_resources, 'styles.css')}"/>

Since the static resource contains both the stylesheet and the image, the relative path in the stylesheet resolves and the image is displayed.
  • Through a custom controller, you can dynamically refer to the contents of a static resource using the <apex:variable> tag. First, create the custom controller:
global class MyController {
    public String getImageName() { 
        return 'Picture.gif';//this is the name of the image 
    }
} 

Then, refer to the getImageName method in your <apex:variable> tag:

<apex:page renderAs="pdf" controller="MyController"> 
    <apex:variable var="imageVar" value="{!imageName}"/> 
    <apex:image url="{!URLFOR($Resource.myZipFile, imageVar)}"/> 
</apex:page>

If the name of the image changes in the zip file, you can just change the returned value in getImageName.



More about Visualforce Tags Examples:
http://sfdcsrini.blogspot.com/2014/06/visualforce-form-tags-with-examples.html







0 comments:

Post a Comment

 
| ,