Registering custom objects for WebContent Templates with TemplateContextContributor

Registering custom objects for WebContent Templates with TemplateContextContributor

Sometimes you may need additional data to be available in the web content template.
TemplateContextContributor can help in this case:
  1. Create class, that implements com.liferay.portal.kernel.template.TemplateContextContributor.
  2. Add @Component annotation to rigister it as OSGi-component.
  3. Override com.lif.app.display.contributor.AppDisplayContributor.prepare(Map<String, Object> contextObjects, HttpServletRequest request) method and put required object into contextObjects map.
  4. Deploy module with template context contributor.
  5. Use registered context in FTL template for web content.
Example:

@Component(
        immediate = true,
        property = "type=" + TemplateContextContributor.TYPE_GLOBAL,
        service = TemplateContextContributor.class)
public class AppDisplayContributor implements TemplateContextContributor {

    private static final String CHARSET_NAME = "UTF-8";
    private static final String PROPS_FILE_NAME = "app.properties";

    private Properties properties = null;

    @Activate    
    public void activate() {
        try {
            ClassLoader classLoader = AppDisplayContributor.class.getClassLoader();
            InputStream is = classLoader.getResourceAsStream(PROPS_FILE_NAME);
            properties = PropertiesUtil.load(Objects.requireNonNull(is), CHARSET_NAME);
        } catch (Exception e) {
            _log.error("Failed to load properties, cause: " + e.getMessage());
        }
    }

    @Override    
    public void prepare(Map<String, Object> contextObjects, HttpServletRequest request) {
        String appDisplayPage = properties.getProperty(AppDisplayKeys.APP_DISPLAY_PAGE_PROP);
        contextObjects.put(AppDisplayKeys.APP_DISPLAY_PAGE_ATTR, appDisplayPage);
    }

    private static final Log _log = LogFactoryUtil.getLog(AppDisplayContributor.class.getName());
}


Note: use TemplateContextContributor.TYPE_GLOBAL type to make it available for web content display. com.liferay.portal.kernel.template.TemplateContextContributor.TYPE_THEME will register context objects for theme only.

Comments

Popular posts from this blog

Liferay Search Container Example

Liferay DXP - max upload file size

Liferay Keycloak integration