Monday, March 28, 2016

Using Liferay Theme resources in layout templates and views

Recently I created a custom theme for a Liferay 6.2 portal along with custom layout templates. I bundled some JavaScript files and images with the theme that were needed. Some of these were jQuery plugins for social media integration, sliders while others were images for backgrounds, tabs etc.

Originally, I was using these resources from the theme by hard coding the theme name into the URL but realized that this was highly inefficient and would break things if the theme name ever changed or got updated to something else.

Luckily Liferay has built in functionality to support dynamically getting resources from the active theme without actually specifying the name of the theme that the resources are being used from. All the information that I needed for this, I found in ThemeDisplay.java.

In this class there are methods that allow end developers to get the path to the js, css, images, templates etc. folders of a theme. Usage inside of a velocity template would be as such:
  • For JS:
    <script src="$theme_display.getPathThemeJavaScript()/mY_js.js"></script>
  • For CSS:
    <link rel="stylesheet" type="text/css" href="$theme_display.getPathThemeCss()/theme.css" />
  • For images:
    <img src="$theme_display.getPathThemeImages()/my_custom_image.gif" alt="..." />
As you can see this makes usage of the active theme in our Liferay views very easy and we avoid hard-coding of the theme name. Of course if there are multiple themes deployed and we wish to use resources from those themes then we would have to resort to hard coding the theme name, but we don't need to do it for the active theme or in a single theme deployment.

No comments:

Post a Comment