Asset Publisher Widget Template: scoping front-end code to a portlet instance

Asset Publisher Widget Template: scoping front-end code to a portlet instance

Overview

Sometimes you need to implement some Javascript and CSS code inside your Asset Publisher Widget Template. It may work properly, but it may be broken when you add a second instance of Asset Publisher with the same Widget Template. This article will show how to "scope" your Javascript/CSS code to the portlet instance only.

Fetch the portletId

First you need to fetch the portletId in Freemarker code of your Widget Template:

<#assign   

   portletId = themeDisplay.getPortletDisplay().getId()

/>


Adjust the Javascript code

Now that you have the portletId, you may use it to fetch the portlet container and bind any javascript events inside it, sample:

$(document).ready(function() {
   var portletId = "${portletId}";
   var $container = $("#portlet_" + portletId);
  
   //todo: bind all events to container, sample:
   /*
   $container.on("click", ".my-btn", function (event) {
       //todo: action-handler
   });
   */
});

Adjust the CSS code

If you have some CSS inside the Widget Template - you may also use the portletId to scope styling only for the portlet instance, sample:


<style>

   #portlet_{portletId} .portlet-body {

       padding-top: 15px;

   }

</style>

 

Enjoy 😏

Comments

Popular posts from this blog

Liferay Search Container Example

Liferay DXP - max upload file size

Liferay Keycloak integration