Reusing Common Code with cfinclude

Often, you use some of the same elements in multiple pages; for example, navigation, headers, and footer code.

Instead of copying and maintaining the same code from page to page, ColdFusion allows you to store the code in one page and then refer to it in many pages. This way, you can modify one file; the changes appear throughout an entire application.

Use the cfinclude tag to automatically include an existing file in the current page. The page that calls the included page is sometimes referred to as the calling page. Each time the calling page is requested, the included page's file contents are added in that page for processing.

For cfinclude syntax, see the CFML Reference.

To reference code in a calling page:

  1. Create a file header.fm that displays your company's logo. Your page could consist of just the following lines or it could include many lines to define an entire header.
    <img src="mylogo.gif">
    
    <br>
    
    

    (Of course, for this code to work you must also put your company's logo as a gif file in the same directory as header.cfm.)

  2. Open the file askemp.cfm in ColdFusion Studio.
  3. Include header.cfm in this page by adding the following line just below the <body> tag:
    <cfinclude template="header.cfm">
    
    
  4. Save the page.
  5. Open getemp.cfm in ColdFusion Studio.
  6. Include the header.cfm file in this page:
    <cfinclude template="header.cfm">
    
    
  7. View askemp.cfm in a browser, then submit the form so that you display getemp.cfm.

    The header should appear on both pages.


Note

The file header.cfm must be in the same directory where you saved askemp.cfm and getemp.cfm (or a subdirectory). If it is not, make sure it is in a directory that has a mapping defined in ColdFusion Administrator, or move it to the appropriate directory.




Banner.Novgorod.Ru